黑马程序员ES6知识笔记

花几秒钟看个开头,你绝对有兴趣继续看下去,里面包含了面向对象的思想,和构造函数,已经对象原型链,箭头函数,数组,字符串添加的新方法,字符串模板,深浅拷贝等知识点。

ES5重点知识

01-创建类和对象

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
	

    <script>
        // 1. 创建类 class  创建一个 明星类
        class Star {
    
    
            constructor(uname, age) {
    
    
                this.uname = uname;
                this.age = age;
            }
        }

        // 2. 利用类创建对象 new
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 20);
        console.log(ldh);
        console.log(zxy);
        //(1) 通过class 关键字创建类, 类名我们还是习惯性定义首字母大写
        //(2) 类里面有个constructor 函数,可以接受传递过来的参数,同时返回实例对象
        //(3) constructor 函数 只要 new 生成实例时,就会自动调用这个函数, 如果我们不写这个函数,类也会自动生成这个函数
        //(4) 生成实例 new 不能省略
        //(5) 最后注意语法规范, 创建类 类名后面不要加小括号,生成实例 类名后面加小括号, 构造函数不需要加function
    </script>
</body>

</html>

02-类中添加方法(1)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 创建类 class  创建一个 明星类
        class Star {
    
    
            // 类的共有属性放到 constructor 里面
            constructor(uname, age) {
    
    
                this.uname = uname;
                this.age = age;
            }
            sing(song) {
    
    
                // console.log('我唱歌');
                console.log(this.uname + song);

            }
        }

        // 2. 利用类创建对象 new
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 20);
        console.log(ldh);
        console.log(zxy);
        // (1) 我们类里面所有的函数不需要写function 
        //(2) 多个函数方法之间不需要添加逗号分隔
        ldh.sing('冰雨');
        zxy.sing('李香兰');
    </script>
</body>

</html>

03-类的继承(1)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 类的继承
        // class Father {
    
    
        //     constructor() {
    
    

        //     }
        //     money() {
    
    
        //         console.log(100);

        //     }
        // }
        // class Son extends Father {
    
    

        // }
        // var son = new Son();
        // son.money();
        class Father {
    
    
            constructor(x, y) {
    
    
                this.x = x;
                this.y = y;
            }
            sum() {
    
    
                console.log(this.x + this.y);

            }
        }
        class Son extends Father {
    
       // extends子类继承父类 子类在前父类在后
            constructor(x, y) {
    
    
                super(x, y); //调用了父类中的构造函数
            }
        }
        var son = new Son(1, 2);
        var son1 = new Son(11, 22);
        son.sum();
        son1.sum();
    </script>
</body>

</html>

04-super关键字调用父类普通函数(1)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // super 关键字调用父类普通函数
        class Father {
    
    
            say() {
    
    
                return '我是爸爸';
            }
        }
        class Son extends Father {
    
    
			
            say() {
    
    
                // console.log('我是儿子');
                console.log(super.say() + '的儿子');
                // super.say() 就是调用父类中的普通函数 say()
            }
        }
        var son = new Son();
        son.say();
        // 继承中的属性或者方法查找原则: 就近原则
        // 1. 继承中,如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就先执行子类的
        // 2. 继承中,如果子类里面没有,就去查找父类有没有这个方法,如果有,就执行父类的这个方法(就近原则)
    </script>
</body>

</html>

05-子类继承父类方法同时扩展自己方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 父类有加法方法
        class Father {
    
    
            constructor(x, y) {
    
    
                this.x = x;
                this.y = y;
            }
            sum() {
    
    
                console.log(this.x + this.y);
            }
        }
        // 子类继承父类加法方法 同时 扩展减法方法
        class Son extends Father {
    
    
            constructor(x, y) {
    
    
                // 利用super 调用父类的构造函数
                // super 必须在子类this之前调用
                super(x, y);
                this.x = x;
                this.y = y;

            }
            subtract() {
    
    
                console.log(this.x - this.y);

            }
        }
		//不能实现匿名对象的操纵
        var son = new Son(5, 3);
        son.subtract();
        son.sum();
    </script>
</body>

</html>

06-使用类注意事项

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button>点击</button>
    <script>
		// 当没有明确的执行时的当前对象时,this指向全局对象window。
        var that;
        var _that;
        class Star {
    
    
            constructor(uname, age) {
    
    
                // constructor 里面的this 指向的是 创建的实例对象(也就是ldh这个对象)
                that = this;
                // console.log(this);

                this.uname = uname;
                this.age = age;
                // this.sing();
				
                this.btn = document.querySelector('button');  //this,btn表示当前正在点击的按钮
                this.btn.onclick = this.sing;  //不能写为this.sing(),如果写成这样,那就会直接调用,不会再点击之后调用。
            }
            sing() {
    
    
                // 这个sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
				//解决方法就是在外面定义一个全局变量,保存实例对象的this,然后再sing()方法里面调用就没问题了
                console.log(this);

                console.log(that.uname+that.age); // that里面存储的是constructor里面的this
            }
            dance() {
    
    
                // 这个dance里面的this 指向的是实例对象 ldh 因为ldh 调用了这个函数
                _that = this;
                console.log(this);

            }
        }

        var ldh = new Star('刘德华',25);
        console.log(that === ldh);
        ldh.dance();
        console.log(_that === ldh);

        // 1. 在 ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象

        // 2. 类里面的共有的属性和方法一定要加this使用.
    </script>
</body>

</html

01-利用构造函数创建对象

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 利用 new Object() 创建对象

        var obj1 = new Object();

        // 2. 利用 对象字面量创建对象

        var obj2 = {
    
    };

        // 3. 利用构造函数创建对象
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
            this.sing = function() {
    
    
                console.log('我会唱歌');

            }
        }

        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 19);
        console.log(ldh);
        ldh.sing();
        zxy.sing();
    </script>
</body>

</html>

02-静态成员和实例成员

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 构造函数中的属性和方法我们称为成员, 成员可以添加
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
            this.sing = function() {
    
    
                console.log('我会唱歌');

            }
        }
        var ldh = new Star('刘德华', 18);
        // 1.实例成员就是构造函数内部通过this添加的成员 uname age sing 就是实例成员
        // 实例成员只能通过实例化的对象来访问
        console.log(ldh.uname);
        ldh.sing();
        // console.log(Star.uname); // 不可以通过构造函数来访问实例成员
        // 2. 静态成员 在构造函数本身上添加的成员  sex 就是静态成员
        Star.sex = '男';
        // 静态成员只能通过构造函数来访问
        console.log(Star.sex);
        console.log(ldh.sex); // 不能通过对象来访问
		 Star.dance=function(){
    
    
			 console.log("我会跳舞");
			
		 }
		 Star.dance()//调用静态方法
    </script>
</body>

</html>

03-原型

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 构造函数的问题. 
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
            // this.sing = function() {
    
    
            //     console.log('我会唱歌');

            // }
        }
        Star.prototype.sing = function() {
    
     //每个构造函数都有一个prototype原型对象
            console.log('我会唱歌');
        }
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 19);
/* 构造函数会每创建一个对象,就会新开辟一个空间来存储this.sing()函数,会造成资源浪费,ldh和zxy这两个对象调用的sing函数不是在同一个内存中,而不是不同的存储空间。

*/
        console.log(ldh.sing === zxy.sing); //比较的是内存地址,返回false
        // console.dir(Star);
        ldh.sing();
        zxy.sing();
        // 2. 一般情况下,我们的公共属性定义到构造函数里面, 公共的方法我们放到原型对象身上
    </script>
</body>

</html>

04-对象原型__proto__

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
        }
        Star.prototype.sing = function() {
    
    
            console.log('我会唱歌');
        }
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 19);
        ldh.sing();
        console.log(ldh); // 每个对象身上系统自己添加一个 (对象的原型)__proto__ 指向我们构造函数的原型对象 prototype
		//__proto__对象原型和原型对象 prototype 是等价的

        console.log(ldh.__proto__ === Star.prototype);
        // 方法的查找规则: 首先先看ldh 对象身上是否有 sing 方法,如果有就执行这个对象上的sing
        // 如果没有sing 这个方法,因为有__proto__ 的存在,就去构造函数原型对象prototype身上去查找sing这个方法
    </script>
</body>

</html>

05-原型constructor

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
        }
		
		   /* 所有引用类型(函数,数组,对象)都拥有__proto__属性(隐式原型)
		    所有函数拥有prototype属性(显示原型)(仅限函数) 
			constructor主要事实用于记录对象引用的是哪个构造函数,他可以让原型对象程序指向原来的构造函数
			*/

        // 很多情况下,我们需要手动的利用constructor(告诉你这个对象是通过那个构造函数来创建的) 这个属性指回 原来的构造函数
        // Star.prototype.sing = function() {
    
    
        //     console.log('我会唱歌');
        // };
        // Star.prototype.movie = function() {
    
    
        //     console.log('我会演电影');
        // }
        Star.prototype = {
    
     //这样的方法会覆盖掉constructor指向Star这个构造函数,所以需要 constructor: Star 来指回原来的构造函数
            // 如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用constructor指回原来的构造函数
            constructor: Star, //指回原来的构造函数
            sing: function() {
    
    
                console.log('我会唱歌');
            },
            movie: function() {
    
    
                console.log('我会演电影');
            }
        }
        var ldh = new Star('刘德华', 18);
        var zxy = new Star('张学友', 19);
        console.log(Star.prototype); //测试prototype(原型对象)对象原型里是否包含constructor
        console.log(ldh.__proto__); //测试__proto__(对象的原型)对象原型里是否包含constructor
        console.log(Star.prototype.constructor);
        console.log(ldh.__proto__.constructor);
    </script>
</body>

</html>

06-原型链

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
        }
        Star.prototype.sing = function() {
    
    
            console.log('我会唱歌');
        }
        var ldh = new Star('刘德华', 18);
        // 1. 只要是对象就有__proto__ 原型, 指向原型对象
        console.log(Star.prototype);
        console.log(Star.prototype.__proto__ === Object.prototype);
        // 2.我们Star原型对象里面的__proto__原型指向的是 Object.prototype
        console.log(Object.prototype.__proto__);
        // 3. 我们Object.prototype原型对象里面的__proto__原型  指向为 null
    </script>
</body>

</html>

07-原型链成员查找规则

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
	<!-- javaScript的查找机制:
	1.当访问一个对象的属性(方法)时,首先查找找着对象自身也没有这个属性。
	2.如果没有就照它的原型,也就是-porto-指向的prototype原型对象。
	3.如果还没有找到原型对象的原型(object的原型对象)
	4.以此类推一直找到objrct位置null5-proto对象原型的意义在于为对象成员查找机制提供一个方向,或者一条路线 
	注意:当多个值冲突时:就近原则,取最近的值。
	-->
    <script>
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
        }
        Star.prototype.sing = function() {
    
    
            console.log('我会唱歌');

        }
        Star.prototype.sex = '女';
        // Object.prototype.sex = '男';
        var ldh = new Star('刘德华', 18);
        ldh.sex = '男';
        console.log(ldh.sex);
        console.log(Object.prototype);
        console.log(ldh);
        console.log(Star.prototype);
        console.log(ldh.toString());
    </script>
</body>

</html>

08-原型对象中this指向

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function Star(uname, age) {
    
    
            this.uname = uname;
            this.age = age;
        }
        var that;
        Star.prototype.sing = function() {
    
    
            console.log('我会唱歌');
            that = this;
        }
        var ldh = new Star('刘德华', 18);
        // 1. 在构造函数中,里面this指向的是对象实例 ldh(谁调用它,它就指向谁)
        ldh.sing();
        console.log(that === ldh);

        // 2.原型对象函数里面的this 指向的是 实例对象 ldh(谁调用它,它就指向谁)
    </script>
</body>

</html>

09-扩展内置对象方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 原型对象的应用 扩展内置对象方法
			
        Array.prototype.sum = function() {
    
    
            var sum = 0;
            for (var i = 0; i < this.length; i++) {
    
    
                sum += this[i];
            }
            return sum;
        };
		// 错误方法,会把原先的方法覆盖掉
        // Array.prototype = {
    
    
        //     sum: function() {
    
    
        //         var sum = 0;
        //         for (var i = 0; i < this.length; i++) {
    
    
        //             sum += this[i];
        //         }
        //         return sum;
        //     }

        // }
        var arr = [1, 2, 3];
        console.log(arr.sum());
        console.log(Array.prototype);
        var arr1 = new Array(11, 22, 33);
        console.log(arr1.sum());
    </script>
</body>

</html>

10-call方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // call 方法
        function fn(x, y) {
    
    
            console.log('我想喝手磨咖啡');
            console.log(this);
            console.log(x + y);


        }
	
        var o = {
    
    
            name: 'andy'
        };
        // fn();
        // 1. call()  //可以调用函数 被调用的函数名称.call()  
        fn.call();
        // 2. call(o) 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象 如果不改变指向的就是window对象
        fn.call(o, 1, 2);
    </script>
</body>

</html>

11-借用父构造函数继承属性

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 借用父构造函数继承属性
        // 1. 父构造函数
        function Father(uname, age) {
    
    
            // this 指向父构造函数的对象实例
            this.uname = uname;
            this.age = age;
			
        }
        // 2 .子构造函数 
        function Son(uname, age, score) {
    
    
            // this 指向子构造函数的对象实例
            Father.call(this, uname, age); //此处改变this的指向问题,把son的this指向的对象传递给father的this,然后son就可以得到uname和age属性
            this.score = score;
        }
        var son = new Son('刘德华', 18, 100);
        console.log(son);
    </script>
</body>

</html>

12-借用原型对象继承方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 借用父构造函数继承属性
        // 1. 父构造函数
        function Father(uname, age) {
    
    
            // this 指向父构造函数的对象实例
            this.uname = uname;
            this.age = age;
        }
        Father.prototype.money = function() {
    
    
            console.log(100000);

        };
        // 2 .子构造函数 
        function Son(uname, age, score) {
    
    
            // this 指向子构造函数的对象实例
            Father.call(this, uname, age);
            this.score = score;
        }
        // Son.prototype = Father.prototype;  这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着一起变化
        Son.prototype = new Father(); //新建一个中间对象
        // 如果利用对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数
        Son.prototype.constructor = Son;
        // 这个是子构造函数专门的方法
        Son.prototype.exam = function() {
    
    
            console.log('孩子要考试');

        }
        var son = new Son('刘德华', 18, 100);
        console.log(son);
        console.log(Father.prototype);
        console.log(Son.prototype.constructor);
		/* 思路:利用 Father.call(this, uname, age);可以让son对象继承father的属性,通过Son.prototype = new Father(); 
		可以让son继承father的方法,但是这样会修改son的constructor,所以需要重新使用Son.prototype.constructor = Son;
		来指向son */
    </script>
</body>

</html>

13-ES6类的本质

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // ES6 之前通过 构造函数+ 原型实现面向对象 编程
        // (1) 构造函数有原型对象prototype 
        // (2) 构造函数原型对象prototype 里面有constructor 指向构造函数本身
        // (3) 构造函数可以通过原型对象添加方法
        // (4) 构造函数创建的实例对象有__proto__ 原型指向 构造函数的原型对象
        // ES6 通过 类 实现面向对象编程 
        class Star {
    
    

        }
        console.log(typeof Star);
        // 1. 类的本质其实还是一个函数 我们也可以简单的认为 类就是 构造函数的另外一种写法
        // (1) 类有原型对象prototype 
        console.log(Star.prototype);
        // (2) 类原型对象prototype 里面有constructor 指向类本身
        console.log(Star.prototype.constructor);
        // (3)类可以通过原型对象添加方法
        Star.prototype.sing = function() {
    
    
            console.log('冰雨');

        }
        var ldh = new Star();
        console.dir(ldh);
        // (4) 类创建的实例对象有__proto__ 原型指向 类的原型对象
        console.log(ldh.__proto__ === Star.prototype);
        i = i + 1;
        i++
    </script>
</body>

</html>

14-forEach方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // forEach 迭代(遍历) 数组
        var arr = [1, 2, 3];
        var sum = 0;
		/* value 数组的每一项元素
		index:数组的索引号,
		array:数组本身 */
        arr.forEach(function(value, index, array) {
    
    
            console.log('每个数组元素' + value);
            console.log('每个数组元素的索引号' + index);
            console.log('数组本身' + array);
            sum += value;
        })
        console.log(sum);
    </script>
</body>

</html>

15-filter筛选数组

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // filter 筛选数组
		/*value 数组的每一项元素
		index:数组的索引号,
		array:数组本身 */
        var arr = [12, 66, 4, 88, 3, 7];
        var newArr = arr.filter(function(value, index) {
    
    
            // return value >= 20;
            return value % 2 === 0; //返回数组的筛选条件
        });
        console.log(newArr);
		 // 1. filter 也是查找满足条件的元素 返回的是一个数组 而且是把所有满足条件的元素返回回来
    </script>
</body>

</html>

16-some查找数组中是否有满足条件的元素

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // some 查找数组中是否有满足条件的元素 
        // var arr = [10, 30, 4];
        // var flag = arr.some(function(value) {
    
    
        //     // return value >= 20;
        //     return value < 3;
        // });
        // console.log(flag);
        var arr1 = ['red', 'pink', 'blue'];
        var flag1 = arr1.some(function(value,index,arr1) {
    
    
            return value == 'pink';
        });
        console.log(flag1);
        // 1. filter 也是查找满足条件的元素 返回的是一个数组 而且是把所有满足条件的元素返回回来
        // 2. some 也是查找满足条件的元素是否存在  返回的是一个布尔值 如果查找到第一个满足条件的元素就终止循环
    </script>
</body>

</html>

17-商品查询案例-利用数组新增方法操作数据

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        table {
    
    
            width: 400px;
            border: 1px solid #000;
            border-collapse: collapse;
            margin: 0 auto;
        }
        
        td,
        th {
    
    
            border: 1px solid #000;
            text-align: center;
        }
        
        input {
    
    
            width: 50px;
        }
        
        .search {
    
    
            width: 600px;
            margin: 20px auto;
        }
    </style>
</head>

<body>
    <div class="search">
        按照价格查询: <input type="text" class="start"> - <input type="text" class="end"> <button class="search-price">搜索</button> 按照商品名称查询: <input type="text" class="product"> <button class="search-pro">查询</button>
    </div>
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>产品名称</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody>


        </tbody>
    </table>
    <script>
        // 利用新增数组方法操作数据
        var data = [{
    
    
            id: 1,
            pname: '小米',
            price: 3999
        }, {
    
    
            id: 2,
            pname: 'oppo',
            price: 999
        }, {
    
    
            id: 3,
            pname: '荣耀',
            price: 1299
        }, {
    
    
            id: 4,
            pname: '华为',
            price: 1999
        }, ];
        // 1. 获取相应的元素
        var tbody = document.querySelector('tbody');
        var search_price = document.querySelector('.search-price');
        var start = document.querySelector('.start');
        var end = document.querySelector('.end');
        var product = document.querySelector('.product');
        var search_pro = document.querySelector('.search-pro');
        setDate(data);
        // 2. 把数据渲染到页面中
        function setDate(mydata) {
    
    
            // 先清空原来tbody 里面的数据
            tbody.innerHTML = '';
            mydata.forEach(function(value) {
    
    
                // console.log(value);
                var tr = document.createElement('tr');
                tr.innerHTML = '<td>' + value.id + '</td><td>' + value.pname + '</td><td>' + value.price + '</td>';
                tbody.appendChild(tr);
            });
        }

        // 3. 根据价格查询商品
        // 当我们点击了按钮,就可以根据我们的商品价格去筛选数组里面的对象
        search_price.addEventListener('click', function() {
    
    
            // alert(11);
            var newDate = data.filter(function(value) {
    
    
                return value.price >= start.value && value.price <= end.value;
            });
            console.log(newDate);
            // 把筛选完之后的对象渲染到页面中
            setDate(newDate);
        });
        // 4. 根据商品名称查找商品
        // 如果查询数组中唯一的元素, 用some方法更合适,因为它找到这个元素,就不在进行循环,效率更高]
        search_pro.addEventListener('click', function() {
    
    
            var arr = [];
            data.some(function(value) {
    
    
                if (value.pname === product.value) {
    
    
                    // console.log(value);
                    arr.push(value);
                    return true; // return 后面必须写true  
                }
            });
            // 把拿到的数据渲染到页面中
            setDate(arr);
        })
    </script>
</body>

</html>

18-forEach和some区别

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        var arr = ['red', 'green', 'blue', 'pink'];
        // 1. forEach迭代 遍历
        // arr.forEach(function(value) {
    
    
        //     if (value == 'green') {
    
    
        //         console.log('找到了该元素');
        //         return true; // 在forEach 里面 return 不会终止迭代
        //     }
        //     console.log(11);

        // })
        // 如果查询数组中唯一的元素, 用some方法更合适,
        arr.some(function(value) {
    
    
            if (value == 'green') {
    
    
                console.log('找到了该元素');
                return true; //  在some 里面 遇到 return true 就是终止遍历 迭代效率更高
            }
            console.log(11);

        });
        // arr.filter(function(value) {
    
    
        //     if (value == 'green') {
    
    
        //         console.log('找到了该元素');
        //         return true; //  // filter 里面 return 不会终止迭代
        //     }
        //     console.log(11);

        // });
    </script>
</body>

</html>

19-trim方法去除两侧空格

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text"> <button>点击</button>
    <div></div>
    <script>
        // trim 方法去除字符串两侧空格
        var str = '   an  dy   ';
        console.log(str);
        var str1 = str.trim();
        console.log(str1);
        var input = document.querySelector('input');
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        btn.onclick = function() {
    
    
            var str = input.value.trim();
            if (str === '') {
    
    
                alert('请输入内容');
            } else {
    
    
                console.log(str);
                console.log(str.length);
                div.innerHTML = str;
            }
        }
    </script>
</body>

</html>

20-Object.keys遍历对象属性

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 用于获取对象自身所有的属性
        var obj = {
    
    
            id: 1,
            pname: '小米',
            price: 1999,
            num: 2000
        };
        var arr = Object.keys(obj);
        console.log(arr);
        arr.forEach(function(value) {
    
    
            console.log(value);

        })
    </script>
</body>

</html>

21-Object.defineProperty方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // Object.defineProperty() 定义新属性或修改原有的属性
        var obj = {
    
    
            id: 1,
            pname: '小米',
            price: 1999
        };
        // 1. 以前的对象添加和修改属性的方式
        // obj.num = 1000;
        // obj.price = 99;
        // console.log(obj);
        // 2. Object.defineProperty() 定义新属性或修改原有的属性
        Object.defineProperty(obj, 'num', {
    
    
            value: 1000,
            enumerable: true
        });
        console.log(obj);
        Object.defineProperty(obj, 'price', {
    
    
            value: 9.9
        });
        console.log(obj);
        Object.defineProperty(obj, 'id', {
    
    
            // 如果值为false 不允许修改这个属性值 默认值也是false
            writable: false,
        });
        obj.id = 2;
        console.log(obj);
        Object.defineProperty(obj, 'address', {
    
    
            value: '中国山东蓝翔技校xx单元',
            // 如果只为false 不允许修改这个属性值 默认值也是false
            writable: false,
            // enumerable 如果值为false 则不允许遍历, 默认的值是 false
            enumerable: false,
            // configurable 如果为false 则不允许删除这个属性 不允许在修改第三个参数里面的特性 默认为false
            configurable: false
        });
        console.log(obj);
        console.log(Object.keys(obj));
        delete obj.address;
        console.log(obj);
        delete obj.pname;
        console.log(obj);
        Object.defineProperty(obj, 'address', {
    
    
            value: '中国山东蓝翔技校xx单元',
            // 如果值为false 不允许修改这个属性值 默认值也是false
            writable: true,
            // enumerable 如果值为false 则不允许遍历, 默认的值是 false
            enumerable: true,
            // configurable 如果为false 则不允许删除这个属性 默认为false
            configurable: true
        });
        console.log(obj.address);
    </script>
</body>

</html>

22.开启严格模式:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <!-- 为整个脚本(script标签)开启严格模式 -->
    <script>
        'use strict';
        //   下面的js 代码就会按照严格模式执行代码
    </script>
    <script>
        (function() {
    
    
            'use strict';
        })();
    </script>
    <!-- 为某个函数开启严格模式 -->
    <script>
        // 此时只是给fn函数开启严格模式
        function fn() {
    
    
            'use strict';
            // 下面的代码按照严格模式执行
        }

        function fun() {
    
    
            // 里面的还是按照普通模式执行
        }
    </script>
</body>

</html>

23.开启严格模式之后的变化:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <!-- 为整个脚本(script标签)开启严格模式 -->
    <script>
        'use strict';
        //   下面的js 代码就会按照严格模式执行代码
    </script>
    <script>
        (function() {
    
    
            'use strict';
        })();
    </script>
    <!-- 为某个函数开启严格模式 -->
    <script>
        // 此时只是给fn函数开启严格模式
        function fn() {
    
    
            'use strict';
            // 下面的代码按照严格模式执行
        }

        function fun() {
    
    
            // 里面的还是按照普通模式执行
        }
    </script>
</body>

</html>

ES6新语法

什么是ES6?
ES 的全称是 ECMAScript , 它是由 ECMA 国际标准化组织,制定的一项脚本语言的标准化规范,ES6 实际上是一个泛指,泛指 ES2015 及后续的版本。

1.使用let关键字声明变量

let声明的变量只在所处于的块级有效

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>使用let关键字声明变量</title>
</head>
<body>
	<script type="text/javascript">
		/*
		
 

			let关键字就是用来声明变量的

			使用let关键字声明的变量具有块级作用域

			在一个大括号中 使用let关键字声明的变量才具有块级作用域 var关键字是不具备这个特点的

			防止循环变量变成全局变量

			使用let关键字声明的变量没有变量提升

			使用let关键字声明的变量具有暂时性死区特性

		*/
		
		/* --------let关键字就是用来声明变量的-------- */
		
		// console.log(a);
	
		
		/* --------使用let关键字声明的变量具有块级作用域-------- */
		// if (true) {
    
    
		// 	let b = 20;
		// 	console.log(b)
		// 	if (true) {
    
    
		// 		let c = 30;
		// 	}
		// 	console.log(c);
		// }
		// console.log(b)
		
		/* -------在一个大括号中 使用let关键字声明的变量才具有块级作用域 var关键字是不具备这个特点的--------- */

		// if (true) {
    
    
		// 	let num = 100;
		// 	var abc = 200;
		// }
		// console.log(abc);
		// console.log(num)


		/* -------防止循环变量变成全局变量--------- */
		// for (let i = 0; i < 2; i++) {}
		// console.log(i);
		

		/*-----使用let关键字声明的变量没有变量提升------*/
		// console.log(a);
		// let a = 100;
		

		/* -------使用let关键字声明的变量具有暂时性死区特性------- */
		var num = 10
		if (true) {
    
    
			console.log(num);
			let num = 20;
		}
		console.log("jjsdf");



	</script>
</body>
</html>

2.使用const声明常量

作用:声明常量,常量就是值(内存地址)不能变化的量。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>使用const关键字声明常量</title>
</head>
<body>
	<script type="text/javascript">
	

		// // 使用const关键字声明的常量具有块级作用域
		// if (true) {
    
    
		// 	const a=10;
		// 	const a = 10;
		// 	if (true) {
    
    
		// 		const a = 20;
		// 		console.log(a);
		// 	}
		// 	console.log(a);
		// }
		// console.log(a);
		
		// 使用const关键字声明的常量必须赋初始值
		// const PI = 3.14;
		
		// 常量声明后值不可更改 
		// const PI = 3.14;
		// // PI = 100;
		const ary = [100, 200];
		ary[0] = 123;
		// ary = [1, 2];
		console.log(ary);
	</script>
</body>
</html>

3.数组结构

数组解构允许我们按照一一对应的关系从数组中提取值 然后将值赋值给变量。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>数组解构</title>
</head>
<body>
	<script type="text/javascript">
		// 数组解构允许我们按照一一对应的关系从数组中提取值 然后将值赋值给变量
		let ary = [1,2,3];
		// let [a, b, c,] = [1,2,3];
		let [a, b, c,] = ary;
		console.log(a+b+c);
	
	</script>
</body>
</html>

4.对象结构

/对象解构允许我们使用变量的名字匹配对象的属性 匹配成功 将对象属性的值赋值给变量。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>对象解构</title>
</head>
<body>
	<script type="text/javascript">
		// 对象解构允许我们使用变量的名字匹配对象的属性 匹配成功 将对象属性的值赋值给变量
		
		let person = {
    
    name: 'lisi', age: 30, sex: '男'};
		// let { name, age, sex } = person;
		// console.log(name)
		// console.log(age)
		// console.log(sex)
		
		let {
    
    name: myName} = person;
		console.log(myName)

	</script>
</body>
</html>

5.箭头函数
注意:箭头函数不绑定this 箭头函数没有自己的this关键字 如果在箭头函数中使用this this关键字将指向箭头函数定义位置中的this。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>箭头函数</title>
</head>
<body>
	<script type="text/javascript">
		// 箭头函数是用来简化函数定义语法的
		// const fn = () => {
    
    
		// 	console.log(123)
		// }
		// fn();
		
		// 在箭头函数中 如果函数体中只有一句代码 并且代码的执行结果就是函数的返回值 函数体大括号可以省略
		// const sum = (n1, n2) => n1 + n2;	 
		// const result = sum(10, 20);
		// console.log(result)
		
		// 在箭头函数中 如果形参只有一个 形参外侧的小括号也是可以省略的
		// const fn = v => {
    
    
		// 	alert(v);
		// }
		// fn(20)
		
		// 箭头函数不绑定this 箭头函数没有自己的this关键字 如果在箭头函数中使用this this关键字将指向箭头函数定义位置中的this
		
		function fn () {
    
    
			console.log(this);
			return () => {
    
    
				console.log(this)
			}
		}

		const obj = {
    
    name: 'zhangsan'};

		const resFn = fn.call(obj);

		resFn();
	</script>
</body>
</html>

6.剩余参数

在箭头函数中,箭头函数中不能使用arguments接收多个参数,但使用扩展运算符(…)的方式可以接收任意个数的参数。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>剩余参数</title>
</head>
<body>
	<script type="text/javascript">
		//剩余参数
		const sum = (...args) => {
    
     //...args表示接收多个参数,箭头函数中不能使用arguments接收多个参数
			let total = 0;
			console.log(typeof args);
			args.forEach(item => total += item);// item表示数组的每一项元素
			return total;
		};
			
		console.log(sum(10, 20));
		console.log(sum(10, 20, 30));
		
				//剩余参数和解构配合使用
		let ary1 = ['张三' , '李四', '王五'];
		let [s1, ...s2] = ary1;
		console.log(s1) //s1接收数组中的第一个值
		console.log(s2)//s2接收s1没有接收剩下的参数,然后s2为一个数组

	</script>
</body>
</html>

7.扩展运算符

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>扩展运算符</title>
</head>
<body>
	<div>1</div>
	<div>2</div>
	<div>3</div>
	
	<script type="text/javascript">
		// 扩展运算符可以将数组拆分成以逗号分隔的参数序列,但是逗号被解析成console.log()的参数分隔符了
		/* let ary = ["a", "b", "c"];
		// ...ary ;// "a", "b", "c"
		console.log(...ary)
		console.log("a", "b", "c")
		 */
		// 扩展运算符应用于数组合并
		/* let ary1 = [1, 2, 3];
		let ary2 = [4, 5, 6];
	
		let ary3 = [...ary1, ...ary2];
		console.log(ary3) */

		// 合并数组的第二种方法
		// let ary1 = [1, 2, 3];
		// let ary2 = [4, 5, 6];

		// ary1.push(...ary2);
		// console.log(ary1)
		
		// 利用扩展运算符将伪数组转换为真正的数组
		var oDivs = document.getElementsByTagName('div');
	
		var ary = [...oDivs];
		ary.push('a');
		console.log(ary);
	</script>
</body>
</html>

8.Array.from方法

作用:用于将伪数组转为真正的数组(需要有length对象的属性才可以)。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Array.from方法</title>
</head>
<body>
	<script type="text/javascript">
		// var arrayLike = {
    
    
		// 	"0": "张三",
		// 	"1": "李四",
		// 	"2": "王五",
		// 	"length": 3
		// }

		// var ary = Array.from(arrayLike);
		// console.log(ary)
		
		var arrayLike = {
    
    
			"0": "1",
			"1": "2",
			"length": 2
		}

		var ary = Array.from(arrayLike, item => item * 2)
		console.log(ary)
	</script>
</body>
</html>

9.find方法介绍

find方法用于查找数组中第一个符合条件的元素,如果没有找到就返回undefined。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>find方法</title>
</head>
<body>
	<script type="text/javascript">
		//find方法用于查找数组中第一个符合条件的元素,如果没有找到就返回undefined
		//item为对象中的每一个元素,index为对象的索引号
		var ary = [{
    
    
			id: 1,
			name: '张三'
		}, {
    
    
			id: 2,
			name: '李四'
		}];
		let target = ary.find((item,index) => item.id == 2);
		console.log(target);
	</script>
</body>
</html>

10. findIndex方法

findIndex方法用于找出第一个符合条件的数组成员,如果没有找到就返回-1

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>findIndex方法</title>
</head>
<body>
	<script type="text/javascript">
		// findIndex方法用于找出第一个符合条件的数组成员,如果没有找到就返回-1
		let ary = [10, 20, 50];
		let index = ary.findIndex(item => item > 15); //找到第一个大于15的索引
		console.log(index)
	</script>
</body>
</html>

11.includes方法

查看一个值是是否包含在数组中,如果包含返回true,不包含返回false

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>include</title>
</head>
<body>
	<script type="text/javascript">
		let ary = ["a", "b", "c"];

		let result = ary.includes('a')
		console.log(result)
		
		result = ary.includes('e')
		console.log(result)
	</script>
</body>
</html>

12.模板字符串

用反引号定义,键盘上esc下面的键
1.模板字符串可以解析变量
2.模板字符串可以换行显示
3.模板字符串是可以调用函数的

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>模板字符串</title>
</head>
<body>
	<script type="text/javascript">
		// 用反引号定义,键盘上esc下面的键
		// 1.模板字符串可以解析变量
		// 2.模板字符串可以换行显示
		// 3.模板字符串是可以调用函数的
		// let name = `张三`;
		// let sayHello = `Hello, 我的名字叫${name}`;
		// console.log(sayHello);
		
		// let result = {
    
    
		// 	name: "zhangsan",
		// 	age: 20
		// };
		// let html = `
		// 	<div>
		// 		<span>${result.name}</span>
		// 		<span>${result.age}</span>
		// 	</div>
		// `;
		// console.log(html);
		
		const fn = () => {
    
    
			return '我是fn函数'
		}

		let html = `我是模板字符串 ${
      
      fn()}`;
		//${fn()}调用fn函数,此处会显示调用函数的返回结果
		console.log(html)

	</script>
</body>
</html>

13.startsWith方法和endsWith方法

startsWith():表示参数字符串是否在原字符串的头部,返回布尔值
endsWith():表示参数字符串是否在原字符串的尾部,返回布尔值

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>startsWith方法和endsWith方法</title>
</head>
<body>
	<script type="text/javascript">
		// startsWith():表示参数字符串是否在原字符串的头部,返回布尔值
		// endsWith():表示参数字符串是否在原字符串的尾部,返回布尔值
		let str = 'Hello ECMAScript 2015';
		let r1 = str.startsWith('Hello');
		console.log(r1);
		let r2 = str.endsWith('2016');
		console.log(r2)
	</script>
</body>
</html>

14.repeat方法

repeat方法表示将原字符串重复n次,返回一个新字符串。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>repeat方法</title>
</head>
<body>
	<script type="text/javascript">
		repeat方法表示将原字符串重复n次,返回一个新字符串。

		console.log("YT,".repeat(5))
	</script>
</body>
</html>

15.Set数据结构

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Set</title>
</head>
<body>
	<script type="text/javascript">
		// Set它类似于数组,但是成员的值都是唯一的,没有重复的值。
		// Set本身是一个构造函数,用来生成  Set  数据结构。
		// add(value):添加某个值,返回 Set 结构本身
		// delete(value):删除某个值,返回一个布尔值,表示删除是否成功
		// has(value):返回一个布尔值,表示该值是否为 Set 的成员
		// clear():清除所有成员,没有返回值
		// Set 结构的实例与数组一样,也拥有forEach方法,用于对每个成员执行某种操作,没有返回值。


		// const s1 = new Set();
		// console.log(s1.size) //查看set存储了多少条数据

		// const s2 = new Set(["a", "b"]);使用数组作为参数传递给set数据结构
		// console.log(s2.size)

		// const s3 = new Set(["a","a","b","b"]); //利用set数据结构做数组去重复
		// console.log(s3.size)
		// const ary = [...s3];
		// console.log(ary)
		
		// const s4 = new Set();
		// 向set结构中添加值 使用add方法
		// s4.add('a').add('b');
		// console.log(s4.size)

		// 从set结构中删除值 用到的方法是delete
		// const r1 = s4.delete('c');
		// console.log(s4.size)
		// console.log(r1);

		// 判断某一个值是否是set数据结构中的成员 使用has
		// const r2 = s4.has('d');
		// console.log(r2)

		// 清空set数据结构中的值 使用clear方法
		// s4.clear();
		// console.log(s4.size);
		
		// 遍历set数据结构 从中取值
		const s5 = new Set(['a', 'b', 'c']);
		s5.forEach(value => {
    
    
			console.log(value)
		})

	</script>
</body>
</html>

到这儿就结束了,虽然这篇文章大多数都是文字,没有图,也没有过多的解释,但是都是有实例代码的,认真看,然后在自己运行一次看结果,也是很容易接受的,希望对大家有所帮助吧。如果文中有错的还请下方评论,大家一起学习,一起进步

猜你喜欢

转载自blog.csdn.net/m0_46188681/article/details/107045339