JS(ES_6)_2

1.创建对象的6种方式:

 1. ob=new Object() ob.name='ah' ob.age=18

2. ob={name:'ah',gae:18}

3.工厂模式:

设计一个函数,专门生产Person类型的对象

<script>
     
        function createPerson(name,age,family) 
            {
                var o = new Object();
                o.name = name;
                o.age = age;
                o.family = family;
                o.say = function(){
                    alert(this.name);
                }
                return o;
            }
            p1=createPerson('ah',18,['l','ys'])
</script>

4.构造函数模式:

构造一个对象Person

<script>
function Person(name,age)
            {
                this.name=name
                this.age=age
                this.sh=Function(){console.log('hi)}
            }
            p1=new Person('ah',18)
</script>

缺陷:构造函数也有其缺陷,每个实例都包含不同的Function实例( 构造函数内的方法在做同一件事,但是实例化后却产生了不同的对象,方法是函数 ,函数也是对象)

5.原型模式创建对象

 

     实例成员:实例化过程中的新加的属性或方法(私有属性或方法)

    静态成员:new 一个对象所具有的基本属性或方法(一般属性或方法)

    公共成员:对象.prototype 的属性或方法,可被重新赋值,可直接使用(公共属性或方法)

prototype见:详解prototype、__proto__和constructor_prototype和constructor-CSDN博客

<script>
        function Person() { }

        console.log(Person.prototype);//Object

        //创建公共属性
        Person.prototype.name = 'ah'
        Person.prototype.age = 21;
        Person.prototype.family = ["lida", "lier", "wangwu"];
        Person.prototype.say = function () {
            alert(this.name);
        };
        console.log(Person.prototype);//{name: 'ah', age: 21, family: Array(3), say: ƒ}

        let p1 = new Person
        console.log(p1);//Person {}
        console.log(p1.name);//ah

        //单独设置私有属性/实例属性:
        p1.sh = function () {
            console.log('hi', this.name);
        }
        console.log(p1);
        console.log(Person.prototype);
        p1.sh()//hi ah

        p2 = new Person
        p2.sh()//报错
    </script>

6.原型模式+构造函数模式:

<script>
        function Person(name, age) {
            this.name = name
            this.age = age
        }//设置一般的属性,方法

        // 公共的的函数
        Person.prototype.sh = function () {
            console.log('hi', this.name);
        }

        console.log(Person);
        /*
        Person(name, age) {
            this.name = name
            this.age = age
        }

        */


        let p1 = new Person('ah', 18)  //设置一般的属性
        p1.sh() // hi ah
        console.log(p1);//Person {name: 'ah', age: 18}
    </script>

2.基本包装类型:

详情见:JS基础知识(二十二):基本包装类型_js包装类型-CSDN博客

1.基本类型值: 指的是简单的数据段Undefined、Null、Boolean、Number 和 String

2.引用类型值: 指那些可能由多个值构成的对象

3.基本包装类型:为了便于操作基本类型值,ECMAScript 还提供了 3 个特殊的引用类型:Boolean、Number 和String。

与其他引用类型相似,但有各自类型相应的特殊方法,例如String的  s1.substring(2);

本来基本类型值不应有方法,但是有方法,这是因为后台自动完成了一系列的处理,即

{

                创建 String 类型的一个实例;

                在实例上调用指定的方法;

                销毁这个实例;

 }经过以上处理,s1就跟个对象一样了而且,上面这三个步骤也分别适用于 Boolean和 Number 类型对应的布尔值和数字值

引用类型  与  基本包装类型  的主要区别就是对象的生存期

使用 new 操作符创建的引用类型的实例,在执行流离开当前作用域之前都一直保存在内存中。

而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁。

3.Object的静态方法:

         1.Object.keys(obj)  返回一个数组,获得属性名

         2.Object.values(obj) 返回一个数组,获得属性值

         3.Object.assign(obj2, obj/{gender:'女'}) 将后者赋值/增加(拷贝)给前者  assign赋值,分配

    <script>
        // 只有构造函数Object可以调用
        // 1.Object.keys(obj)  返回一个数组,获得属性名
        // 2.Object.values(obj) 返回一个数组,获得属性值
        // 3.Object.assign(obj2, obj) 将后者赋值(拷贝)给前者
        let obj = {
            name: 'ah',
            age: 18,
            sh: function () {
                alert(this.name)
            }
        }
        console.log(Object.keys(obj));
        console.log(Object.values(obj));

        let obj2 = {}
        Object.assign(obj2, obj)// 后者给前者
        console.log(obj2);
        // let arr = Object.keys(obj)
        // console.log(arr[0]);
        // console.log(arr[1]);
    </script>

4.Array的实例方法:

 1.forEach:遍历,无返回值,本质上等同于 for 循环,对每一项执行 function 函数。

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = [1, 2, 3]
        let sum = 0
        arr.forEach(function (e) { sum += e })
        console.log(sum); //6
    </script>
</body>

</html>

2.map:迭代映射,map() 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const array1 = [1, 4, 9, 16];

        // Pass a function to map
        const map1 = array1.map((x) => x * 2);

        console.log(map1);
        // Expected output: Array [2, 8, 18, 32]
    </script>
</body>

</html>

 3.reduce:累计器

使用方法:

<script>
        const array1 = [1, 2, 3, 4];

        // 0 + 1 + 2 + 3 + 4
        const initialValue = 0; //initialValue初始值
        const sumWithInitial = array1.reduce(
            (accumulator, currentValue) => accumulator + currentValue,  //accumulator累加器  currentValue数组值
            initialValue,
        );

        console.log(sumWithInitial);
        // Expected output: 10
    </script>

相关过程:         

  第一次调用回调时初始化 accumulator 的值。

            如果指定了 initialValue,则 callbackFn 从数组中的第一个值作为 currentValue 开始执行,accumulator初始为initialValue

            如果没有指定 initialValue,则 accumulator 初始化为数组中的第一个值,并且 callbackFn 从数组中的第二个值作为 currentValue 开始执行。

            在这种情况下,如果数组为空(没有第一个值可以作为 accumulator 返回),则会抛出错误。

            每次调用时,callbackFn 的返回值都作为 accumulator 参数传递到下一次调用中。

            accumulator 的最终值(也就是在数组的最后一次迭代中从 callbackFn 返回的值)将作为 reduce() 的返回值

4.filter:过滤返回数组

filter() 方法创建给定数组一部分的浅拷贝,其包含 通过所提供函数实现的测试 的所有元素。

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // filter() 方法创建给定数组一部分的浅拷贝,其包含 通过所提供函数实现的测试 的所有元素。
        const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];

        const result = words.filter((word) => word.length > 6);

        console.log(result);
        // Expected output: Array ["exuberant", "destruction", "present"]
    </script>
</body>

</html>

5.join:整合

 join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。 如果数组只有一个元素,那么将返回该元素而不使用分隔符。

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const elements = ['Fire', 'Air', 'Water'];

        console.log(elements.join());
        // Expected output: "Fire,Air,Water"

        console.log(elements.join(''));
        // Expected output: "FireAirWater"

        console.log(elements.join('-'));
        // Expected output: "Fire-Air-Water"
    </script>
</body>

</html>

6.find:查找第一个符合条件的,有则返回,无则undifind,可以用来根据对象的属性筛选对象

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const array1 = [5, 12, 8, 130, 44];

        const found = array1.find((element) => element > 10);//括号内写查找的函数/要求

        console.log(found);
        // Expected output: 12
    </script>
</body>

</html>

7.every:测试所有元素

every() 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const isBelowThreshold = (currentValue) => currentValue < 40;

        const array1 = [1, 30, 39, 29, 10, 13];

        console.log(array1.every(isBelowThreshold));
        // Expected output: true

    </script>
</body>

</html>

8.some:测试是否包含

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = [1, 2, 3, 4]
        console.log(arr.some(x => x == 1)); //true

    </script>
</body>

</html>

9.findindex:找index,返回要找元素的下标,没找到则返回-1

使用方法:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = ['a', 'b', 'c', 'd']
        console.log(arr.findIndex(x => x == 'c'));

    </script>
</body>

</html>

特殊:Array.from():伪数组(可迭代对象)转真数组

例如将获得的 lis 数组转化成真数组

案例:购物车展示

效果图:

代码:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
            box-sizing: border-box;
        }

        .banner {
            width: 1000px;
            height: 500px;
            margin: 0 auto;
            padding: 0 20px;
            border: 1px solid #000;
        }

        li {
            display: flex;
            width: 100%;
            height: 100px;
            margin-bottom: 6px;
            justify-content: space-between;
        }

        li img {
            width: 100px;
        }

        li div {
            width: 250px;
            text-align: center;
            color: red;
        }

        li span {
            color: #b3b3b3a5;
            font-size: 13px;
        }

        li .title {
            width: 100%;
            text-align: left;
            color: #000;
        }

        .total {
            text-align: right;
        }

        .total span {
            color: red;
        }
    </style>
</head>

<body>
    <div class="banner">
        <ul>
            <!-- 样例布局,可留可删 -->
            <li>
                <img src="https://img10.360buyimg.com/jdcms/s460x460_jfs/t1/163511/10/41642/167436/65e18381Fa56cd005/a3dd2c0fa6881ad0.jpg.webp"
                    alt="">
                <div class="title">诚心如意手摇咖啡磨豆机<br><span>【赠品】</span><br><span>【赠品】</span></div>
                <div><span>青色/一大</span></div>
                <div>289.90</div>
                <div><span>x2</span></div>
                <div>279.80</div>
            </li>
        </ul>
        <div class="total">合计:<span>798.00¥</span></div>
    </div>

    <script>
        const goodlists = [
            {
                name: 'Apple 苹果 iPhone 15 Plus 二手手机 蓝色 128G',
                price: 4999,
                picture: 'https://img20.360buyimg.com/jdcms/s460x460_jfs/t1/182034/34/38675/27903/650a62f5F522fd836/10fd8e1d1809b325.jpg.webp',
                count: 2,
                spec: { color: '蓝色' },
                gifts: '充电线,耳机'
            },
            {
                name: '电脑台式桌家用办公桌子卧室小型简约租房学生学习写字桌简易书桌 经典款-100CM白柳木 圆滑桌角 稳固承重',
                price: 116,
                picture: 'https://img12.360buyimg.com/jdcms/s460x460_jfs/t1/219000/19/39060/94643/65fdb31dF791b2494/d73fccc8ca386203.jpg.webp',
                count: 1,
                spec: { size: '150cm*100cm', color: '原木色' }
            },
            {
                name: '科技布艺沙发小户型客厅卧室简约单人双人三人北欧简易服装店网红 深蓝色 科技布 80cm 单人位【厂家直销】',
                price: 888,
                picture: 'https://img11.360buyimg.com/jdcms/s460x460_jfs/t1/112292/24/44663/84229/65d19513F0af948f9/105acfa9e3bdc391.jpg.webp',
                count: 1,
                spec: { size: '3m*1.5m', color: '紫色' }
            }
        ]


        const ul = document.querySelector('.banner ul')
        const total = document.querySelector('.banner .total')
        let subtotal = [] //求和
        ul.innerHTML = goodlists.map(function (e) {
            subtotal.push(e.count * e.price)
            let str = ``
            if (Object.keys(e).find(x => x == 'gifts')) {
                // let arr = Object.values(e.gifts).join('').split(',')
                let arr = e.gifts.split(',')
                console.log(arr);
                for (x of arr) {
                    str += `<br><span>【赠品】${x}</span>`
                }
            }
            return `
            <li>
                <img src="${e.picture}"
                    alt="">
                <div class="title">${e.name}${str}</div>
                <div><span>${Object.values(e.spec).join('/')}</span></div>
                <div>${e.price.toFixed(2)}</div>
                <div><span>x${e.count}</span></div>
                <div>${e.count * e.price}</div>
            </li>`
        }).join('')


        let initialvalue = 0

        total.innerHTML = `合计:<span>${subtotal.reduce((a, initialvalue) => a + initialvalue)}¥</span>`



    </script>
</body>

</html>

  • 26
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值