• 23~49(构造函数+继承+类的本质+ES5中的新增方法)


    1 构造函数和原型

    1.1 概述

    在典型的OOP的语言中(如Java),都存在类的概念,类就是对象的模板,对象就是类的实例,但在ES6之前,JS中并没用引入类的概念。

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

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

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

    1. 对象字面量
    2. new Object()
    3. 自定义构造函数

    1.2 构造函数

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

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

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

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

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

    • 静态成员:在构造函数本上添加的成员称为静态成员,只能由构造函数本身来访问
    • 实例成员: 在构造函数内部创建的对象成员称为实例成员,只能由实例化的对象来访问
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <script>
            // 构造函数中的属性和方法称为成员,成员可以添加
            function Star(uname, age) {
                this.uname = uname;
                this.age = age;
                this.sing = function() {
                    console.log('我会唱歌');
                }
            }
            var ldh = new Star('刘德华', 18);
            // 实例成员就是构造函数内部通过this添加的成员 uname age sing 就是实例成员
            // 实例成员只能通过实例化的对象来访问
            console.log(ldh.uname);
            ldh.sing();
            // console.log(Star.uname); // 不可以通过构造函数来访问实例成员
            // 2. 静态成员 在构造函数本身上添加的成员
            Star.sex = '男';
            // 静态成员只能通过构造函数来访问
            console.log(Star.sex);
            console.log(ldh.sex); // 不能通过对象来访问
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    1.3 构造函数的问题

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

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wCEsrZiT-1666192723564)(…/images/构造函数的问题.png)]

    更希望的是:所有的对象使用同一个函数,这样就比较节省内存

    1.4 构造函数原型 prototype

    构造函数通过原型分配的函数是所有对象所共享的

    JavaScript规定,每一个构造函数都有一个prototype属性,指向另一个对象。意这个prototype就是一
    个对象,这个对象的所有属性和方法,都会被构造函数所拥有。

    我们可以把那些不变的方法,直接定义在prototype对象上,这样所有对象的实例就可以共享这些方法。

    总结
    1. 原型是什么?
      一个对象,我们也称为prototype为原型对象

    2. 原型的作用是什么?
      共享方法

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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('张学友', 18);
            // console.dir(Star);
            ldh.sing();
            zxy.sing();
            //  2. 一般情况下,公共属性定义到构造函数里面, 公共的方法放到原型对象身上
    
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    1.5 对象原型 proto

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

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

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f2Pn0keo-1666192723565)(…/images/proto.png)]

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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('张学友', 18);
            ldh.sing();
            console.log(ldh); // 对象身上系统自己添加一个 _proto_ 指向我们构造函数的原型对象
            console.log(ldh.__proto__ === Star.prototype); // 返回true
            // 方法的查找规则:首先先看ldh对象身上是否有sing方法 如果有就执行这个对象上的sing
            // 如果没有sing这个方法 因为__proto__的存在,就去构造函数原型对象prototype身上去查找sing这个方法
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    1.6 constructor 构造函数

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

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

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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('张学友', 18);
            console.log(Star.prototype);
            console.log(ldh.__proto__);
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

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

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MXydAHRi-1666192723566)(…/images/关系.png)]

    1.8 原型链

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jKKSdY0k-1666192723567)(…/images/原型链.png)]

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <script>
            function Star(uname, age) {
                this.uname = uname;
                this.age = age;
            }
            Star.prototype.sing = function() {
                console.log('我会唱歌');
            };
            var ldh = new Star('刘德华', 18);
            // 只要是对象就有__proto__原型 指向原型对象
            console.log(Star.prototype);
            console.log(Star.prototype.__proto__ == Object.prototype);
            // Star原型对象里卖弄的__proto原型指向的是Object.prototype
            console.log(Object.prototype.__proto__);
            // 3. Object.prototype原型对象里面的__proto__原型 指向为null
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

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

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

    1.10 原型对象this指向

    1. 在构造函数中,里面this指向的是对象实例
    2. 原型对象函数里面的this指向的是实例对象
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    1.11 扩展内置对象

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

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

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    2 继承

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

    2.1 call()

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

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

    • thisArg :当前调用函数this的指向对象
    • arg1,arg2 :传递的其他参数 上

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <script>
            // call方法
            function fn(x, y) {
                console.log('我想喝手磨咖啡');
                console.log(this);
                console.log(x + y);
            }
            var o = {
                name: 'yaya'
            }
            // fn();
            // 1. call()可以调用函数
            // fn.call();
            // 2. call()可以改变这个函数的this指向 此时这个函数的this就指向了o这个对象
            fn.call(o, 1, 2);
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

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

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

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

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

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <script>
            // 借用父构造函数继承属性
            // 1. 父构造函数
            function Father(uname, age) {
                // this指向父构造函数的对象实例
                this.uname = uname;
                this.age = age;
            }
            Father.prototype.money = function() {
                console.log(10000);
            }
            // 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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    3 类的本质

    1. class本质还是function.
    2. 类的所有方法都定义在类的prototype属性上
    3. 类创建的实例,里面也有__proto__指向类的prototype原型对象
    4. 所以ES6的类它的绝大部分功能, ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
    5. 所以ES6的类其实就是语法糖.
    6. 语法糖:语法糖就是一种便捷写法. 简单理解,有两种方法可以实现同样的功能,但是一种写法更加清晰、方便,那么这个方法就是语法糖

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <script>
            // ES6之前通过 构造函数 + 原型实现面向对象编程
    
            // 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)类创建的实例对象有__prototype__ 原型指向类的原型对象
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    4 ES5中的新增方法

    4.1 ES5新增方法概述

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

    • 数组方法
    • 符串方法
    • 对象方法

    4.2 数组方法

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

    1. forEach()

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

    • currentValue: 数组当前项的值
    • index: 数组当前项的索引
    • arr: 数组对象本身

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    1. filter()

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

    • filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素,主要用于筛选数组
    • 注意它直接返回一个新数组
    • currentValue:数组当前项的值
    • index :数组当前项的索引
    • arr :数组对象本身

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <script>
            // filter筛选数组
            var arr = [12, 66, 4, 88, 3, 7];
            var newArr = arr.filter(function(value, index, array) {
                // return value >= 20;
                return value % 2 === 0;
            });
            console.log(newArr);
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    1. some()

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

    • some()方法用于检测数组中的元素是否满足指定条件.通俗点查找数组中是否有满足条件的元素
    • 注意它返回值是布尔值。如果查找到这个元素,就返回true,如果查找不到就返回false.
    • 如果找到第一个满足条件的元素,则终止循环不在继续查找.
    • currentValue:数组当前项的值
    • index :数组当前项的索引
    • arr :数组对象本身

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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);
            // filter 也是查找满足条件的元素 返回的是一个数组 而且是把所有满足条件的元素返回回来
            // some 是查找满足条件的元素是否存在 返回的是一个布尔值 如果查找到第一个满足条件的元素就终止循环
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    查找商品案例
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>17-利用数组新增方法操作数据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>idth>
                    <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');
            setData(data);
            // 2. 把数据渲染到页面中
            function setData(mydata) {
                // 先清空原来tbody里面的数据
                tbody.innerHTML = '';
                mydata.forEach(function(value) {
                    // console.log(value);
                    var tr = document.createElement('tr');
                    tr.innerHTML = '' + value.id +'' + value.pname + '' + value.price + '';
                    tbody.appendChild(tr);
                });
            }
            
            // 3. 根据价格查询商品
            // 当我们点击了按钮,就可以根据我们的商品价格去筛选数组里面的对象
            search_price.addEventListener('click', function() {
                var newData = data.filter(function(value) {
                    // console.log(value);
                    return value.price >= start.value && value.price <= end.value; 
                });
                console.log(newData);
                // 把筛选完之后的对象渲染到页面中
                setData(newData);
            });
            // 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
                    }
                });
                // 把拿到的数据渲染到页面中
                setData(arr);
            })
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113

    效果如下:

    商品查询案例

    forEach() some() filter()区别
    • forEach()和filter()里面return不会终止迭代

    • some()里面遇到return true就是终止遍历 迭代效率更高

    eg:

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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);
            // });
            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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    4.3 字符串方法

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

    str.trim()

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

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    4.4 对象方法

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

    Object.keys(obj)

    • 效果类似for…in
    • 返回一个由属性名组成的数组
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    1. Object.defineProperty()定义对象中新属性或修改原有的属性。

    object.defineProperty(obj, prop, descriptor)

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

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

    • value: 设置属性的值默认为undefined
    • writable: 值是否可以重写。true | false 默认为false
    • enumerable: 目标属性是否可以被枚举。true | false 默认为false
    • configurable: 目标属性是否可以被删除或是否可以再次修改特性true | false默认为false
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
  • 相关阅读:
    Hive实战-表创建
    第五章《类的继承》第3节:方法的重写
    verilog刷题笔记
    NAND Flash原理
    java 文件上传 MultipartFile
    基于HTML5实现动态烟花秀效果(含音效和文字)实战
    labview与stm32通信
    [html] 动态炫彩渐变背景
    2022 年 Java 行业分析报告
    单元测试-学习笔记
  • 原文地址:https://blog.csdn.net/m0_57809042/article/details/127418105