JavaScript 高级2 :构造函数和原型

JavaScript 高级2 :构造函数和原型

Date: January 16, 2023
Text: 构造函数和原型、继承、ES5中的新增方法


目标

能够使用构造函数创建对象

能够说出原型的作用

能够说出访问对象成员的规则

能够使用 ES5新增的一些方法




构造函数和原型

概述

在典型的 OOP 的语言中(如 Java),都存在类的概念,类就是对象的模板,

对象就是类的实例,但在 ES6之前, JS 中并没用引入类的概念。

ES6, 全称 ECMAScript 6.0 ,2015.06 发版。但是目前浏览器的 JavaScript 是 ES5 版本,大多数高版本的浏览器也支持 ES6,不过只实现了 ES6 的部分特性和功能。

在 ES6之前 ,对象不是基于类创建的,而是用一种称为构建函数的特殊函数来定义对象和它们的特征。

创建对象可以通过以下三种方式:

  1. 对象字面量

  2. new Object()

  3. 自定义构造函数

案例:

  • Code:

    <!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>
    

注意:以上的几种方法都是ES6之前的方式,现在是用类的方式来创建



构造函数

构造函数是一种特殊的函数,主要用来初始化对象,即为对象成员变量赋初始值,它总与 new 一起使用。我们可以把对象中一些公共的属性和方法抽取出来,然后封装到这个函数里面。

在 JS 中,使用构造函数时要注意以下两点:

  1. 构造函数用于创建某一类对象,其首字母要大写
  2. 构造函数要和 new 一起使用才有意义

new 在执行时会做四件事情:

  1. 在内存中创建一个新的空对象。
  2. 让 this 指向这个新的对象。
  3. 执行构造函数里面的代码,给这个新对象添加属性和方法。
  4. 返回这个新对象(所以构造函数里面不需要 return )。

JavaScript 的构造函数中可以添加一些成员,可以在构造函数本身上添加,也可以在构造函数内部的 this 上添加。通过这两种方式添加的成员,就分别称为静态成员和实例成员。

**静态成员:**在构造函数本上添加的成员称为静态成员,只能由构造函数本身来访问

**实例成员:**在构造函数内部创建 的对象成员称为实例成员,只能由实例化的对象来访问

案例:

  • Code:

    <!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); // 不能通过对象来访问
        </script>
    </body>
    
    </html>
    

总结:

构造函数主要用于初始化对象

静态成员:在构造函数本身上添加的成员,比如Star.sex = '男';,静态成员只能通过构造函数来访问

实例成员:在构造函数内部通过this添加的成员,实例成员只能通过实例化的对象来访问,比如console.log(ldh.uname); ldh.sing();



构造函数的问题

构造函数方法很好用,但是存在浪费内存的问题。

Untitled

我们希望所有的对象使用同一个函数,这样就比较节省内存,那么我们要怎样做呢?

案例:

  • code:

    <!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() {
                console.log('我会唱歌');
            }
            var ldh = new Star('刘德华', 18);
            var zxy = new Star('张学友', 19);
            console.log(ldh.sing === zxy.sing);  // 返回的是false
            // console.dir(Star);
            ldh.sing();
            zxy.sing();
            // 2. 一般情况下,我们的公共属性定义到构造函数里面, 公共的方法我们放到原型对象身上
        </script>
    </body>
    
    </html>
    

总结:

问题:

如果我们在构造函数中创建成员函数,那么在创建不同对象时,也会创建彼此相依的成员函数,这会导致内存的重复占用问题

解决方案:

一般情况下,我们的公共属性定义到构造函数里面, 公共的方法我们放到原型对象身上

Star.prototype.sing = function() {
    console.log('我会唱歌');
} 



构造函数原型 prototype

对象原型( proto)和构造函数(prototype)原型对象里面都有一个属性 constructor 属性 ,constructor 我们称为构造函数,因为它指回构造函数本身。

constructor 主要用于记录该对象引用于哪个构造函数,它可以让原型对象重新

指向原来的构造函数。

一般情况下,对象的方法都在构造函数的原型对象中设置。如果有多个对象的方法,我们可以给原型对象采取对象形式赋值,但是这样就会覆盖构造函数原型对象原来的内容,这样修改后的原型对象 constructor 就不再指向当前构造函数了。此时,我们可以在修改后的原型对象中,添加一个 constructor 指向原来的构造函数。

案例:

  • Code:

    <!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() {
                console.log('我会唱歌');
            }
            var ldh = new Star('刘德华', 18);
            var zxy = new Star('张学友', 19);
            console.log(ldh.sing === zxy.sing);  // 返回的是false
            // console.dir(Star);
            ldh.sing();
            zxy.sing();
            // 2. 一般情况下,我们的公共属性定义到构造函数里面, 公共的方法我们放到原型对象身上
        </script>
    </body>
    
    </html>
    

总结:

  1. 原型是什么?

    一个对象,我们也称prototype为原型对象

  2. 原型的作用是什么?

    共享方法,节省内存资源

注意:

一般情况下,我们的公共属性定义到构造函数里面, 公共的方法我们放到原型对象身上



对象原型 **proto**

对象都会有一个属性_proto_ 指向构造函数的 prototype 原型对象,之所以我们对象可以使用构造函数 prototype 原型对象的属性和方法,就是因为对象有 **proto** 原型的存在。

**proto**对象原型和原型对象 prototype 是等价的

**proto**对象原型的意义就在于为对象的查找机制提供一个方向,或者说一条路线,但是它是一个非标准属性,因此实际开发中,不可以使用这个属性,它只是内部指向原型对象 prototype

Untitled

  • Code:

    <!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;
            }
            // 很多情况下,我们需要手动的利用constructor 这个属性指回 原来的构造函数
            // Star.prototype.sing = function() {
            //     console.log('我会唱歌');
            // };
            // Star.prototype.movie = function() {
            //     console.log('我会演电影');
            // }
            Star.prototype = {
                // 如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用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);
            console.log(ldh.__proto__);
            console.log(Star.prototype.constructor);
            console.log(ldh.__proto__.constructor);
        </script>
    </body>
    
    </html>
    

总结:

对象有对象原型__proto__,它指向原型对象prototype, 因此对象可以使用公共函数。



constructor 构造函数

对象原型( proto)和构造函数(prototype)原型对象里面都有一个属性 constructor 属性 ,

constructor 我们称为构造函数,因为它指回构造函数本身。

constructor 主要用于记录该对象引用于哪个构造函数,它可以让原型对象重新指向原来的构造函数。

一般情况下,对象的方法都在构造函数的原型对象中设置。如果有多个对象的方法,我们可以给原型对象采取对象形式赋值,但是这样就会覆盖构造函数原型对象原来的内容,这样修改后的原型对象 constructor 就不再指向当前构造函数了。此时,我们可以在修改后的原型对象中,添加一个 constructor 指向原来的构造函数。

  • Code:

    <!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;
            }
            // 很多情况下,我们需要手动的利用constructor 这个属性指回 原来的构造函数
            // Star.prototype.sing = function() {
            //     console.log('我会唱歌');
            // };
            // Star.prototype.movie = function() {
            //     console.log('我会演电影');
            // }
            Star.prototype = {
                // 如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用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);
            console.log(ldh.__proto__);
            console.log(Star.prototype.constructor);
            console.log(ldh.__proto__.constructor);
        </script>
    </body>
    
    </html>
    


构造函数、实例、原型对象三者之间的关系

Untitled



原型链

Untitled

  • Code:

    <!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>
    


JavaScript 的成员查找机制(规则)

  1. 当访问一个对象的属性(包括方法)时,首先查找这个对象自身有没有该属性。
  2. 如果没有就查找它的原型(也就是 __proto__指向的 prototype 原型对象)。
  3. 如果还没有就查找原型对象的原型(Object的原型对象)。
  4. 依此类推一直找到 Object 为止(null)。
  5. __proto__对象原型的意义就在于为对象成员查找机制提供一个方向,或者说一条路线。
  • Code:

    <!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('我会唱歌');
    
            }
            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>
    


原型对象this指向

构造函数中的this 指向我们实例对象.

原型对象里面放的是方法, 这个方法里面的this 指向的是 这个方法的调用者, 也

就是这个实例对象.(谁调用,this指向谁)

  • Code:

    <!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>
    


扩展内置对象

可以通过原型对象,对原来的内置对象进行扩展自定义的方法。比如给数组增加自定义求偶数和的功能。

注意:数组和字符串内置对象不能给原型对象覆盖操作 Array.prototype = {} ,只能是Array.prototype.xxx = function(){} 的方式。

  • Code:

    <!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>
    



继承

ES6之前并没有给我们提供 extends 继承。我们可以通过构造函数+原型对象模拟实现继承,被称为组合继承。

call()

调用这个函数, 并且修改函数运行时的 this 指向

fun.call(thisArg, arg1, arg2, ...)

thisArg :当前调用函数 this 的指向对象

arg1,arg2:传递的其他参数

  • Code:

    <!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() 可以调用函数
            // fn.call();
            // 2. call() 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象
            fn.call(o, 1, 2);
        </script>
    </body>
    
    </html>
    


借用构造函数继承父类型属性

核心原理: 通过 call() 把父类型的 this 指向子类型的 this ,这样就可以实现子类型继承父类型的属性。

// 父类    
function Person(name, age, sex) {      
		this.name = name;      
		this.age = age;      
		this.sex = sex;    
}    
// 子类    
function Student(name, age, sex, score) {      
		Person.call(this, name, age, sex);// 此时父类的 this 指向子类的 this,同时调用这个函数      
		this.score = score;    
}    
var s1 = new Student('zs', 18, '男', 100);    
console.dir(s1);
  • Code:

    <!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.score = score;
            }
            var son = new Son('刘德华', 18, 100);
            console.log(son);
        </script>
    </body>
    
    </html>
    


借用原型对象继承父类型方法

一般情况下,对象的方法都在构造函数的原型对象中设置,通过构造函数无法继承父类方法。

核心原理:

  1. 将子类所共享的方法提取出来,让子类的 prototype 原型对象 = new 父类()
  2. 本质:子类原型对象等于是实例化父类,因为父类实例化之后另外开辟空间,就不会影响原来父类原型对象
  3. 将子类的 constructor 从新指向子类的构造函数
  • Code:

    <!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);
        </script>
    </body>
    
    </html>
    
  • Code:

    <!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);
        </script>
    </body>
    
    </html>
    


类的本质

  1. class本质还是function.

  2. 类的所有方法都定义在类的prototype属性上

  3. 类创建的实例,里面也有__proto__ 指向类的prototype原型对象

4.所以ES6的类它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

5.所以ES6的类其实就是语法糖.

  1. 语法糖:语法糖就是一种便捷写法. 简单理解, 有两种方法可以实现同样的功能, 但是一种写法更加清晰、方便,那么这个方法就是语法糖
  • Code:

    <!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>
    



ES5 中的新增方法

ES5 新增方法概述

ES5 中给我们新增了一些方法,可以很方便的操作数组或者字符串,这些方法

主要包括:数组方法、字符串方法、对象方法



数组方法

迭代(遍历)方法:forEach()、map()、filter()、some()、every();

array.forEach(function(currentValue, index, arr))

currentValue:数组当前项的值

index:数组当前项的索引

arr:数组对象本身

  • Code:

    <!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;
            arr.forEach(function(value, index, array) {
                console.log('每个数组元素' + value);
                console.log('每个数组元素的索引号' + index);
                console.log('数组本身' + array);
                sum += value;
            })
            console.log(sum);
        </script>
    </body>
    
    </html>
    

array.filter(function(currentValue, index, arr))

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素,主要用

于筛选数组
注意它直接返回一个新数组

currentValue: 数组当前项的值

index:数组当前项的索引

arr:数组对象本身

  • Code:

    <!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 筛选数组
            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);
        </script>
    </body>
    
    </html>
    

array.some(function(currentValue, index, arr))

some() 方法用于检测数组中的元素是否满足指定条件.

通俗点 查找数组中是否有满足条件的元素

注意它返回值是布尔值, 如果查找到这个元素, 就返回true , 如果查找不到就返回false.如果找到第一个满足条件的元素,则终止循环. 不在继续查找.

currentValue: 数组当前项的值

index:数组当前项的索引

arr:数组对象本身

  • Code:

    <!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) {
                return value == 'pink';
            });
            console.log(flag1);
            // 1. filter 也是查找满足条件的元素 返回的是一个数组 而且是把所有满足条件的元素返回回来
            // 2. some 也是查找满足条件的元素是否存在  返回的是一个布尔值 如果查找到第一个满足条件的元素就终止循环
        </script>
    </body>
    
    </html>
    

总结:

  1. filter 也是查找满足条件的元素 返回的是一个数组 而且是把所有满足条件的元素返回回来
  2. some 也是查找满足条件的元素是否存在 返回的是一个布尔值 如果查找到第一个满足条件的元素就终止循环


查询商品案例

  1. 把数据渲染到页面中 (forEach)
  2. 根据价格显示数据
  3. 根据商品名称显示数据
  • Code:

    <!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>
    

拓展:forEach和some区别

循环找到相应数据时,forEach和filter若return true不会终止循环,而some则会终止循环,效率更高。即,如果我们想要在数组中查找唯一的元素,用some方法更合适。

  • Code:

    <!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>
    


字符串方法

trim() 方法会从一个字符串的两端删除空白字符。

str.trim()

trim() 方法并不影响原字符串本身,它返回的是一个新的字符串。

  • Code:

    <!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>
    


对象方法

  1. Object.keys() 用于获取对象自身所有的属性
Object.keys(obj)

效果类似 for…in
返回一个由属性名组成的数组

  • Code:

    <!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>
    

  1. Object.defineProperty() 定义对象中新属性或修改原有的属性。(了解)
Object.defineProperty(obj, prop, descriptor)

obj:必需。目标对象
prop:必需。需定义或修改的属性的名字
descriptor:必需。目标属性所拥有的特性

  • Code:

    <!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>
    

Object.defineProperty() 定义新属性或修改原有的属性。

Object.defineProperty(obj, prop, descriptor)

Object.defineProperty() 第三个参数 descriptor 说明: 以对象形式 { } 书写

value: 设置属性的值 默认为undefined

writable: 值是否可以重写。true | false 默认为false

enumerable: 目标属性是否可以被枚举。true | false 默认为 false

configurable: 目标属性是否可以被删除或是否可以再次修改特性 true | false 默认为false




猜你喜欢

转载自blog.csdn.net/CaptainDrake/article/details/129231970