JS(ES_6)_2

news2024/10/6 14:38:23

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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1693385.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

WebGL的室内设计软件

WebGL (Web Graphics Library) 是一个JavaScript API&#xff0c;它提供了一种在网页上渲染3D图形的方法&#xff0c;无需使用插件。利用WebGL&#xff0c;开发者可以创建和展示复杂的3D场景&#xff0c;包括室内设计。以下是开发基于WebGL的室内设计软件时可能涉及的一些关键步…

如何禁止U盘拷贝文件|禁止U盘使用的软件有哪些

禁止U盘拷贝文件的方法有很多&#xff0c;比如使用注册表、组策略编辑器等&#xff0c;但这些方法都适合个人&#xff0c;不适合企业&#xff0c;因为企业需要对下属多台电脑进行远程管控&#xff0c;需要方便、省时、省力的方法。目前来说&#xff0c;最好的方法就是使用第三方…

水表电表远程抄表是什么?

1.简述&#xff1a;水表电表远程抄表技术性 随着时代的发展&#xff0c;传统式手动抄表方法早已被更为高效、智能化的远程抄表系统所替代。水表电表远程抄表&#xff0c;说白了&#xff0c;就是利用互联网技术完成对水表和电表读数的远程数据采集管理方法&#xff0c;大大提升…

Css提高——Css的动画与3D转换

Css动画 1、动画元素的使用步骤 制作动画分为两步&#xff1a; 先定义动画再使用&#xff08;调用&#xff09;动画 2、用keyframes定义动画 keyframes 动画名称 {0%{width:100px;} 100%{width:200px;} }其中的0%和100%可以理解为给动画打上了开始和结束的两个关键帧 3、动…

kotlinx.coroutines.debug.AgentPremain

大家好 我是苏麟 . 项目引入AI大模型 debug 出现报错 设置 勾选

ES升级--01--环境准备和安装

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 Linux 单机1.官网下载 Elasticsearchhttps://www.elastic.co/cn/downloads/past-releases/#elasticsearch 2.解压软件3.创建用户设置用户 es 密码 es赋权ES用户数据…

小林coding笔记

MySQL执行流程 MySQL 的架构共分为两层&#xff1a;Server 层和存储引擎层。Server 层负责建立连接、分析和执行 SQL。存储引擎层负责数据的存储和提取。 Mysql执行 启动Mysql net start mysql登陆 mysql -u root -p输入密码

clangd failed: Couldn‘t build compiler instance问题解决!!!

如果其他人的博客不能解决问题&#xff0c;可以试试我的解决方案&#xff1a; 修改compile_commands.json中cc为arm-linux-gnueabihf-gcc&#xff0c; 例如&#xff1a; 之后&#xff0c;clangd就能用了&#xff0c;虽然输出也会报错&#xff0c;但好歹能用了

五管OTA输入极性快速判断

做CMFB还有负反馈的时候曾经在判断输入输出极性上吃了大亏&#xff0c;直接做实验波形正确就是输入正端&#xff0c;全差分就不用考虑这么多了 和弯折&#xff0c;形状类似7&#xff0c;相同方向输入正端&#xff0c;相反的就是输入负端&#xff0c;输出也是和输入负端一个方向…

K8S认证|CKA题库+答案| 12. 查看Pod日志

12、查看Pod日志 您必须在以下Cluster/Node上完成此考题&#xff1a; Cluster Master node Worker node k8s master …

Rust腐蚀怎么用服务器一键开服联机教程

1、进入控制面板 首次登陆需要点击下方重置密码&#xff0c;如何再点击登录面板&#xff0c;点击后会跳转到登录页面&#xff0c;输入用户名和密码登录即可 2、设置游戏端口 由于腐蚀的设置需要三个端口&#xff0c;它们用于游戏端口&#xff08;必须为首选端口&#xff09;&a…

二十八篇:嵌入式系统实战指南:案例研究与未来挑战

嵌入式系统实战指南&#xff1a;案例研究与未来挑战 1. 引言 1.1 嵌入式系统的重要性及其应用广度 在当今快速发展的技术领域中&#xff0c;嵌入式系统扮演着至关重要的角色。这些系统是专门设计的计算机硬件和软件的组合&#xff0c;旨在执行特定任务&#xff0c;如控制、监…

【Apache Doris】周FAQ集锦:第 4 期

【Apache Doris】周FAQ集锦&#xff1a;第 4 期 SQL问题数据操作问题运维常见问题其它问题关于社区 欢迎查阅本周的 Apache Doris 社区 FAQ 栏目&#xff01; 在这个栏目中&#xff0c;每周将筛选社区反馈的热门问题和话题&#xff0c;重点回答并进行深入探讨。旨在为广大用户和…

03-02-Vue组件之间的传值

前言 我们接着上一篇文章 03-01-Vue组件的定义和注册 来讲。 下一篇文章 04-Vue&#xff1a;ref获取页面节点–很简单 父组件向子组件传值 我们可以这样理解&#xff1a;Vue实例就是一个父组件&#xff0c;而我们自定义的组件&#xff08;包括全局组件、私有组件&#xff09;…

C# GDI+ 绘制文字不同的操作系统渲染文字大小不同

一、C# GDI 绘制文字不同的操作系统渲染文字大小不同 原因&#xff1a;使用Font 字体的时候&#xff0c;没有指定字体渲染的单位。 不同系统的默认字体单位会不同。 二、解决方案&#xff1a; 在指定字体的时候&#xff0c;指定字体大小&#xff0c;同时也要设置字体的单位 …

基于FMU的Star CCM+与Amesim复杂控制联合分析

1、背景: 当前Star CCM+的逻辑控制功能并不强大,当需要仿真复杂多变的工况时往往力不从心。为了解决该问题,当前有两个方案可以尝试,分别如下: 方案1:利用AMEsim与Star CCM+联合仿真,通过tcp传输模块来实现两者的实时耦合。 方案2:利用AMEsim导出FMU文件,然后将FMU…

部署PIM-SM

拓扑图 配置 使能组播路由 配置OSPF 组播路由器接口配置pim-sm 连接组成员的接口使能igmp pim路由器上配置静态RP sysname AR1 # multicast routing-enable # interface GigabitEthernet0/0/0ip address 10.1.12.1 255.255.255.0 pim sm # interface GigabitEthernet0/0/…

软件设计师备考 | 案例专题之数据流图 概念与例题

案例分析专题大纲&#xff1a; 数据流图基本概念 基本图形元素&#xff1a;外部实体、加工、数据存储、数据流 数据流&#xff1a;由一组固定成分的数据组成&#xff0c;表示数据的流向。在DFD中&#xff0c;数据流的流向必须经过加工。加工&#xff1a;描述了输入数据流到输出…

idea 出现 cpu占用100%

一、IDEA的CPU占用率过高 二、解决办法 idea安装路径bin目录 修改idea64.exe.vmoptions配置文件 原来的 -Xms128m -Xmx750m -XX:ReservedCodeCacheSize240m -XX:UseConcMarkSweepGC -XX:SoftRefLRUPolicyMSPerMB50 修改为(IDEA优化内存配置) -Xms2048m -Xmx4096m -XX:Reser…

基于Spring Boot的高校图书馆管理系统

项目和论文都有企鹅号2583550535 基于Spring Boot的图书馆管理系统||图书管理系统_哔哩哔哩_bilibili 第1章 绪论... 1 1.1 研究背景和意义... 1 1.2 国内外研究现状... 1 第2章 相关技术概述... 2 2.1 后端开发技术... 2 2.1.1 SpringBoot 2 2.1.2 MySQL.. 2 2.1.3 My…