JavaScript入门学习笔记


1、什么是JavaScript

1.1、概述

JavaScript是一门世界上最流行的脚本语言。

Java、JavaScript 并没有什么关系。

一个合格的后端人员,必须要精通JavaScript

1.2、历史

https://blog.csdn.net/kese7952/article/details/79357868

ECMAScript它可以理解为是JavaScript的一个标准

最新版本已经到es6版本~

但是大部分浏览器还只停留在支持es5代码上!

开发环境---线上环境,版本不一致

2、快速入门

2.1、引入JavaScript

1、内部引入

    

2、外部引入

ads.js

//...

test.html


测试代码:



    
        
        MyFirstJavaScriptCoding

        

        
		
        
        
        
        
    
    
        
        
    

2.2、基本语法入门



    
        
        

        
        
    
    

    

2.3、数据类型

数值、文本、图形、音频、视频...

变量

var num

number

JS不区分小数和整数、number

123//整数123
123.1//浮点数123.1
123e3//科学计数法
-99//负数
NaN// not a number
Infinity//表示无限大

字符串

'abd' "abc"

布尔值

true false

逻辑运算

&& 
|| 
!

比较运算符

= 赋值
== 等于(类型不一样、值一样,也会判断为true)
=== 绝对等于(类型一样、值一样,结果为true)
var a = '1';
undefined
var b = 1;
undefined
console.log(a == b);
VM1217:1 true
undefined
console.log(a === b);
VM1232:1 false
undefined

这是JS的缺陷,坚持不要使用 == 比较。

须知:

  • NaN === NaN,这个与所有的数值都不相等,包括自己
  • 只能通过isNaN(NaN)来判断这个数是否是NaN

浮点数问题:

1/3 == (1 - 2/3)
false

尽量避免使用浮点数进行计算,存在精度问题

Math.abs(1/3 - (1-2/3)) < 0.00000001
true

null和undefined

  • null 空
  • undefined 未定义

数组

//保证代码的可读性,尽量使用[]
var arr = [1,2,3,'hello',null,true];

new Array(1,2,3,'hello',null,true);

取数组下标:如果越界了就会

undefined

对象

对象是大括号,数组是中括号

每个属性之间使用逗号隔开,最后一个不用写逗号

var person = {
    name: "January",
    age: 22,
    tags: ['js', 'java', 'python', '...']
}

取对象的值

person.name
"January"

2.4、严格检查模式



    
        
        
    
    
    
    
    

3、数据类型

3.1、 字符串

1、正常字符串我们使用单引号或者双引号包裹

2、注意转义字符 \

\'
\n
\t
\u4e2d \u#### Unicode字符
\x41				Ascll字符

3、多行字符串编写

//tab键上边esc键下边 
console.log(`
            你好,IU
            你好,奈良
            你好,世界
            `)

4、模板字符串

let name = "xionglei";
let age = 22;
let msg = `你好啊, ${name}`;

5、字符串长度

str.length

6、字符串的可变性,不可变

7、大小写转换

//注意这里是方法,不是属性
name.toUpperCase();
name.toLowerCase();

8、获取指定字符串的索引

indexOf() lastIndexOf()

9、截取字符串

substring() slice() split()

name.substring(1,3);	//左闭右开 [1,3)
//slice() 与 substring() 功能基本相同,下面是不同点
name.substring(2,-2);	//xi [0,2) 
name.slice(2,-2);		//ongl [2,name.length-2)即[2,6)
name.substring(-2,2);	//xi [0,2)
name.slice(-2,2);		//""

这些方法执行后都是返回新的字符串,不会改变原始字符串。

注意:

如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。

String.split() 执行的操作与 Array.join 执行的操作是相反的。

3.2、数组

Array可以包含任意的数据类型

arr = [1,2,3,4,5,6];//通过下标取值赋值
arr[0] = 1;

1、长度

arr.length

注意:假如给arr.length赋值,数组大小就会发生变化。如果赋值过小,元素就会丢失。

2、indexOf()通过元素或得下标索引

arr.indexOf(2)
1

字符串的“1”与数字1是不同的。

3、slice()截取Array的一部分,与字符串中的slice几乎相同。

4、push() pop() 尾部

push(): 压入到尾部
pop() : 弹出尾部的一个元素

5、unshift() shift() 头部

unshift(): 压入到头部
shift()  : 弹出头部的一个元素

6、排序 sort()

arr = ["a","c","b"];
arr.sort();
> (3) ["a","b","c"];

7、元素反转

arr = ["a","b","c"];
arr.reverse();
> (3) ["c","b","a"]

8、concat()

arr = ["a","b","c"];
arr.concat(1,2,3);
(6) ["c", "b", "a", 1, 2, 3]
arr
(3) ["c", "b", "a"]

注意:concat() 并没有修改数组,只是返回了一个新数组。

9、连接符 join()

打印拼接数组,使用特定的字符串连接。

(3) ["c", "b", "a"]
arr.join("-");
"c-b-a"

10、多维数组

arr = [[1,2],[3,4],['5',"6"]];
(3) [Array(2), Array(2), Array(2)]
arr[1][1];
4

11、fill() 给数组对应索引上的元素赋值

arr = [1,2,3];
(3) [1, 2, 3]
arr.length = 10;
10
arr
(10) [1, 2, 3, empty × 7]
arr.fill(0, 3, -1);
(10) [1, 2, 3, 0, 0, 0, 0, 0, 0, empty]

数组:存储数据。(如何存 如何取,方法都可以自己实现)

3.3、对象

若干个键值对

var 对象名 = {
    属性名: 属性值,
    属性名: 属性值,
    属性名: 属性值
}
//定义了一个person对象,有四个属性
var person = {
                name : "xionglei",
                age : 22,
                email : "xionglei1614@163.com",
                score : 145
            }

JavaScript中对象,{......}表示一个对象,键值对描述属性xxx: xxx,多个属性之间用逗号隔开,最后一个属性不加逗号!

JavaScript中所有的键都是字符串,值是任意对象

1、对象赋值

person.name = "IU";
"IU"
person.name
"IU"

2、使用一个不存在的对象属性,不会保存

person.IU
undefined

3、动态的删减属性

delete person.name;
true
person
{age: 22, email: "xionglei1614@163.com", score: 145}

4、动态的添加属性

person.IU = "IU";
"IU"
person
{age: 22, email: "xionglei1614@163.com", score: 145, IU: "IU"}

5、判断属性值是否在这个对象中! xx in XXX!

'age' in person;
true
//继承
'toString' in person;
true

6、判断一个属性是否是这个对象自身拥有的 hasOwnProperty()

person.hasOwnProperty('toString');
false
person.hasOwnProperty('age');
true

3.4、流程控制

if判断

let age = 3;
if(age < 3) {
    alert("wuwu");
}else if(age === 3) {
    alert("heihei");
}else{
    alert("haha");
}

while 循环,避免死循环

let age = 90;
while(age < 100) {
    console.log(age);
    age++;
}

do{
    console.log(age);
    age++;
}while(age < 100);

for循环

for(let i = 0; i < 10; i++) {
    console.log(i);
}

forEach循环

5.1引入

arr = [1,2,3,4,5,6,"1",'2'];
arr.forEach(function (value) {
    console.log(value);
});

for...in

arr
(8) [1, 2, 3, 4, 5, 6, "1", "2"]
for(let index in arr){
    console.log(arr[index]);
};

3.5、 Map和Set

ES6中的新特性

Map:

let map = new Map([['tom', 100], ['jack', 90], ['LiMing', 88]]);
undefined
map.get('tom');//获取
100
map.set('XiaoMei', 99);//新增或修改
Map(4) {"tom" => 100, "jack" => 90, "LiMing" => 88, "XiaoMei" => 99}
map.delete('tom');//删除

Set: 无序不重复的集合

let set = new Set([3,1,1,1,2,2]);
set.add(4);//增
Set(4) {3, 1, 2, 4}
set.delete(1);//删除
true
set.has(4);//判断是否存在
true

3.6、iterator

ES6

遍历器(Iterator)是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。

在ES6中,有三类数据结构原生具备Iterator接口:数组、某些类似数组的对象、Set和Map结构。具备Iterator接口不用任何处理,就可以被for...of循环遍历

具体请参考JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。

  • 简洁和清晰的层次结构使得JSON成为理想的数据交互语言。
  • 易于人的阅读和编写,同时也易于机器解析和生成,有效地提高网络传输效率。
  • 在JavaScript一切皆为对象,任何JavaScript支持的类型都可以用JSON来表示。

    格式:

    • 对象都用{}
    • 数组都用[]
    • 所有的键值对 都是用key:vue

    JSON和JavaScript对象的转化

    let user = {
        name: 'IU',
        birth: '1993-05-16',
    }
    //对象转化为JSON字符串 "{"name":"IU","birth":"1993-05-16"}"
    let JSONUserString = JSON.stringify(user);
    //JSON字符串转化为对象
    let obj = JSON.parse('{"name":"IU","birth":"1993-05-16"}');
    

    JSON和JS对象的区别

    let obj = {name: "IU", birth: "1993-05-16", age: 20}
    let json = '{"name":"IU","birth":"1993-05-16","age":20}'
    

    5.3、Ajax

    • 原生的JavaScript写法 xhr异步请求

    • jQuery封装好的写法 $. ("#id").ajax("");

    • axios 请求

    6、面向对象编程

    6.1、什么是面向对象

    • 类:模板 原型对象
    • 对象:具体的实例

    JavaScript有些区别

    原型

    let xiaowang = {
        name: 'xiaowang',
        age: 22,
        introduce: function() {
            console.log('Hello Every One, I`m ' + this.name);
        }
    }
    let xiaomei = {
        name: 'xiaomei',
        age: 21
    }
    //原型对象
    xiaomei.__proto__ = xiaowang;
    

    类的定义与使用

    //ES6之前
                function Student(name,age){
                    this.name = name;
                    this.age = age;
                }
                // 在不改变Student的代码情况下,给Student新增一个方法
                Student.prototype.introduce = function () {
                    console.log(('Hi, gays! I`m ' + this.name));
                }
                //使用类创建对象
                let Tom = new Student('Tom', 21);
                let IU = new Student('IU', 26);
    
                Student.prototype.Category = '人类';
    

    class

    class关键字在ES6引入

    1. 定义一个类,属性方法
    // ES6 使用class关键字
    class Animal{
        //构造器
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        //方法
        introduce() {
            console.log('Hello, Every! My name is ' + this.name);
        }
    }
    let tomcat = new Animal('tomcat', '128');
    tomcat.introduce();//Hello, Every! My name is tomcat
    
    1. 继承
      实现本质:原型
    class Cat extends Animal {
        constructor(name, age, color) {
            super(name, age);
            this.color = color;
        }
        //方法
        sayColor() {
            this.introduce();//此处的可用this或super但不能省略
            console.log('my color is ' + this.color);
        }
    }
    let lan = new Cat('lan', 23, 'bule');
    lan.introduce();
    lan.sayColor();
    
    1. 原型链

    __proto__

    具体参考这个博客,感觉已经将得很详细了。

    7、操作BOM对象(重点)

    BOM:浏览器对象模型

    window(重要)

    window代表浏览器窗口

    window.location = 'http://www.163.com';
    window.history
    History {length: 8, scrollRestoration: "auto", state: null}
    window.innerHeight
    282
    window.outerHeight
    831
    window.innerWidth
    764
    window.outerWidth
    779//根据浏览器放大缩小会变
    

    封装了浏览器的信息(不建议使用)

    navigator.appVersion
    "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
    navigator.userAgent
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
    
    

    大多数时候我们不会使用navigator对象,因为会被人为修改。不建议使用这些使用来判断和编写代码。

    screen

    screen.width
    1536
    screen.height
    864//屏幕的尺寸
    

    location(重要)

    代表当前页面的URL信息

    > location.host
    < "www.163.com"
    > location.href
    < "https://www.163.com/"
    > location.protocol
    < "https:"
    > location.reload
    < ? reload() { [native code] }//刷新网页
    //设置新地址
    location.assign('http://www.baidu.com');//访问原地址时自动跳转到新的地址
    

    document

    代表当前页面,HTML DOM文档树

    > document.title = 'IU'
    < "IU"
    

    获取具体的文档树节点

    document.getElementByID('input1');
    

    获取cookie

    > document.cookie
    < "BIDUPSID=32FC51FB55EB481A622C93E99780C3E2; PSTM=1563450097; BD_UPN=12314753; BAIDUID=B49DE68C77D501F651F3A26E9A4B7848:FG=1; MCITY=-%3A; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; COOKIE_SESSION=7_0_6_2_32_6_0_0_2_5_1_0_80695_0_1466_0_1586184214_0_1586182748%7C9%23103222_674_1585054542%7C9; BD_HOME=1; H_PS_PSSID=1436_31124_21085_31186_30908_31218_30823_31086_31163_22160; __yjsv5_shitong=1.0_7_b8fa8c7efc803bd805652debd5d24eba6f17_300_1586241772083_171.95.58.217_95ff1766"
    

    history(不建议使用)

    history.back();//后退
    history.forword();//前进
    

    8、操作DOM对象(重点)

    DOM:文档对象模型

    核心

    浏览器网页就是一个Dom树形结构

    • 更新
    • 遍历 通过选择器得到节点
    • 删除
    • 添加

    要操作一个Dom节点,就必须要先或得这个Dom节点

    获得节点

    //对应css选择器
    let h1 = document.getElementsByTagName('h1');//标签选择器
    let p1 = document.getElementById('p1');
    let classP1 = document.getElementsByClassName('classP1');
    let father = document.getElementById('father');
    let childrens = father.children;//获取父节点下的多有子节点
    

    这回事最原始的JS代码。

    更新节点

    let id1 = document.getElementById('id1');
    
    id1.innerText = 'Hello, IU';
    id1.innerHTML = '点击跳到百度'
    
    • 操作文本:
    id1.innerText='Hello, IU' // 修改文本的值
    id1.innerHTML = '点击跳到百度';// 可以解析HTML文本标签
    
    • 操作css
    id1.style.id1.style.fontSize='50px';//属性石红字符串包裹
    id1.style.paddingLeft = '100px'//注意命名与css不一样
    

    删除节点

    删除节点的步骤:获取父节点,然后通过父节点删除自己。

    你还,IU

    你还,IU

    你还,IU

    let father = document.getElementById('div1');
    father.remove(father.children[2]);
    father.remove(father.children[1]);
    father.remove(father.children[0]);
    

    删除子节点的时候,fathe.children的值是不断变化的,因此想要删除多个,要下标从大到小删除

    插入节点

    若获取的元素为空是,可以使用innerHtml。若不为空,则使用z追加操作。

    • 追加
    
    

    JavaScript

    Python

    Java

    SQL

    //把已有标签移动到任意标签后面
    let js = document.getElementById('js');
    let div = document.getElementById('div');
    div.append(js);
    //创建一个新标签实现插入
    let span = document.createElement('span');
    span.innerText = '这是新创建的';
    div.appendChild(span);
    //通过setAttribute可以设置任意属性的值
    let myScript = document.createElement('script');
    myScript.setAttribute('type', 'text/javaScript');
    let myHead = document.getElementsByTagName('head');
    myHead[0].append(myScript);
    
    • insertBefore
    //div.insertBefore(node, child);
    div.insertBefore('js', p2);//在div的子节点p2前面插入节点js
    
    • replaceChild
    //div.replaceChild(node,child);注意被替换的child节点会变为node,node从原来位置移动到了child处。相当于,删除了child,并把node移动到了child的位置
    div.replaceChild(js, p2);//把div的子节点p2替换为js
    

    9、操作表单

    文本框	text
    下拉框	
                

    性别:

    提交填单(验证)

    
    
        
            
            提交表单
            
            
        
        
            

    用户名:

    密码:

    10、jQuery

    jQuery库,里面封装了大量的JavaScript方法。

    CDN jQuery

           
    

    使用jQuery万能公式:$(selector).action()

    基础使用

    
    
        
            
            初始jQuery
            
            
        
        
            点我
    
            
        
    
    

    选择器

    • 原生JavaScript
    //原生JavaScript选择器少,且复杂
    document.getElementById();//id
    document.getElementsByTagName();//标签
    document.getElementsByClassName();//类
    
    • jQuery
    //与css相同
    $('#id')//id
    $('a');//标签
    $('.class1');//类
    

    文档工具站:点击此处跳转

    事件

    • 鼠标事件

    • 键盘事件

    • 其他事件

    获取鼠标的坐标并实时显示:

    
    
        
            
            事件
            
            
        
        
            
            mouse:
            
    在这里移动鼠标试试

    操作DOM

    • 节点文本操作
    $('ul li[name=python]');//取值
    $('ul li[name=python]').text('python <( ̄︶ ̄)↗[GO!]');//赋值
    $('ul').html();//取值
    $('ul').html($('ul').html() + '
  • 设置值
  • ');//设置值
    • 操作css
    $("p").css("color");//查看css中color属性的值
    $('p').css({ "color": "#ff0011", "background": "blue" });//给一组css属性赋值
    $("p").css("color","red");//给一个css属性赋值
    //参数name,回调函数 描述:
    //点击div使其变大
    $("div").click(function() {
        $(this).css({
            width: function(index, value) {
                return parseFloat(value) * 1.2;
            }, 
            height: function(index, value) {
                return parseFloat(value) * 1.2;
            }
        });
    });
    
    • 元素的显示和隐藏: 本质display: none
    $('div').show();//显示
    $('div').hide();//隐藏
    $('div').toggle();//切换
    
    • ajax
    $.ajax({ url: "test.html", context: document.body, success: function(){
        $(this).addClass("done");
    }});
    

    ajax为重点,详情请参考这里

    总结

    • 如何巩固js

    看jQuery源码

    看游戏源码

    • 如何巩固HTML,CSS

    扒网站,全部down下来,然后对应修改看效果