当前位置: 首页 > news >正文

JavaScript进阶笔记--深入对象-内置构造函数及案例

深入对象

创建对象三种方式

  1. 利用对象字面量
  2. new Object({…})
  3. 利用构造函数
// 1. 字面量创建对象const obj1 = {name: 'pig',age: 18};console.log(obj1); // {name: "pig", age: 18}// 2. 构造函数创建对象function Pig(name, age) {this.name = name;this.age = age;};const obj2 = new Pig('piki', 19);console.log(obj2);const obj3 = new Object({name: 'pigDaddy',age: 45})console.log(obj3);// 3. Object.create()方法创建对象const obj4 = Object.create(null);obj4.name = 'piggy';obj4.age = 20;console.log(obj4);

构造函数

【快速创建多个类似对象】 – 技术上常规函数,

但,

  • 命名以字母大写开头
  • 只能由“new”操作符执行 ==> 实例化

不用写return,写了也无效

过程

  1. 创建新对象
  2. 构造函数this指向新对象
  3. 执行构造函数代码
  4. 返回新对象
 // 构造函数function Goods(name, price, count) {this.name = name;this.price = price;this.count = count;}// 创建实例对象const mi = new Goods('xiaomi', 1999, 20);const wei = new Goods('huawei', 3999, 59);const vivo = new Goods('vivo', 1888, 100);// 输出实例对象的属性console.log(mi.name); // xiaomiconsole.log(mi.price); // 1999console.log(mi.count); // 20console.log(wei.name); // huaweiconsole.log(wei.price); // 3999console.log(wei.count); // 59console.log(vivo.name); // vivoconsole.log(vivo.price); // 1888console.log(vivo.count); // 100

实例&静态成员

分类

  • 实例成员:实例对象中的属性和方法(结构相同但值不同)
  • 静态成员:构造函数的属性和方法 – 相当于c++中的静态关键字static

静态成员方法中的this指向构造函数本省,如Math.random()就是静态方法

// 静态对象function Person() {this.name = 'John';this.age = 30;}//静态属性Person.eyes = 2;Person.arms = 2;//静态方法Person.walk = function () {console.log("你应该会走路吧,孩子");console.log(this.eyes);}Person.walk(); // 你应该会走路吧,孩子 2

内置构造函数

==> 字符串,数值,布尔值等都有方法和竖向【JS底层进行包装】

Object

==> 用于创建普通对象

Object.keys – 返回一个数组,关于对象的属性名

Object.values – 返回一个数组,关于对象的属性值

Object.assign(obj1,obj2) – 将obj2对象中的内容,复制到obj1中,多用于追加属性

name: '张三',age: 20}console.log(Object.keys(obj));console.log(Object.values(obj));//返回的是数组类型const obj1 = {name: 'ls',age: 26}Object.assign(obj1, { gender: 'man' })console.log(obj1);

Array

reduce – 返回累计处理结果,用于求和

返回一个值

语法

arr.reduce(function(上一次值,当前值){},初始值)

若由初始值,则改变累加结果

上一次值为

  • 一开始第一次循环为初始值,若无,则为0
  • 后来为上一次的上一次值+当前值

累加的过程总共循环n次

const arr = [1, 2, 3, 4, 5];const all = arr.reduce((pre, cur) => pre + cur, 0);console.log(all);const all2 = arr.reduce((pre, cur) => pre + cur, 10);console.log(all2);
方法作用
join将数组元素拼接为字符串
find查找元素,返回第一个符合条件的元素,若没,则返回undefinded
every如果所有元素都符合条件,则返回true,否则,则返回false
some判断元素中如果由符合条件的,就返回true,否则,则返回false
concat合并两个数组,返回一个新的数组
sort对原数组的元素进行排序
splice删除或替换原数组单元
findIndex根据数组元素值来查找对应的索引值,若找不到,返回-1
reverse反转数组,返回一个新数组
// join传参为拼接分隔符
const arr = ['I', 'am', 'spider', 'man'];const str = arr.join(' ');console.log(str);//findconst arr = [1, 2, 3, 4, 5];const isSix = arr.find((item) => item === 4);console.log(isSix);//every返回布尔值const arr = [1, 2, 3, 4, 5];const BigtoZero = arr.every(item => item > 0);console.log(BigtoZero);//some返回布尔值const arr = [3, 2, 4, 6, 8];const isOne = arr.some(item => item % 2 === 1)console.log(isOne);
//concatconst arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const newArr = arr1.concat(arr2);console.log(newArr);
//sortconst arr = [5, 3, 1, 2, 4];const sortArr = arr.sort((a, b) => b - a);console.log(sortArr);
//spliceconst arr = [1, 2, 2, 3, 4, 5, 6];const newarr = arr.splice(2);console.log(newarr);
//reverse
const arr = [5, 4, 3, 2, 1];const reverseArr = arr.reverse();console.log(reverseArr);
//findIndexconst arr = [1, 2, 3, 4, 5];const Three = arr.findIndex(item => item === 6);console.log(Three);
  • splice方法的注释

    start: 指定修改的起始位置。

  • deleteCount: 表示要删除的元素数量。如果设置为0,则不会删除元素。

  • item1, …, itemN: 要添加到数组中的新元素。

Number

toFixed(n) – 保留几位小数,四舍五入,默认不保留小数

综合案例

根据后台提供的数据,渲染购物车页面

[!IMPORTANT]

如何有效利用JS方法来高效处理数据并渲染到页面上

<!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>Document</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}.list {width: 990px;margin: 100px auto 0;}.item {padding: 15px;transition: all .5s;display: flex;border-top: 1px solid #e4e4e4;}.item:nth-child(4n) {margin-left: 0;}.item:hover {cursor: pointer;background-color: #f5f5f5;}.item img {width: 80px;height: 80px;margin-right: 10px;}.item .name {font-size: 18px;margin-right: 10px;color: #333;flex: 2;}.item .name .tag {display: block;padding: 2px;font-size: 12px;color: #999;}.item .price,.item .sub-total {font-size: 18px;color: firebrick;flex: 1;}.item .price::before,.item .sub-total::before,.amount::before {content: "¥";font-size: 12px;}.item .spec {flex: 2;color: #888;font-size: 14px;}.item .count {flex: 1;color: #aaa;}.total {width: 990px;margin: 0 auto;display: flex;justify-content: flex-end;border-top: 1px solid #e4e4e4;padding: 20px;}.total .amount {font-size: 18px;color: firebrick;font-weight: bold;margin-right: 50px;}</style>
</head><body><div class="list"><!-- <div class="item"><img src="https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg" alt=""><p class="name">称心如意手摇咖啡磨豆机咖啡豆研磨机 <span class="tag">【赠品】10优惠券</span></p><p class="spec">白色/10寸</p><p class="price">289.90</p><p class="count">x2</p><p class="sub-total">579.80</p></div> --></div><div class="total"><div>合计:<span class="amount">1000.00</span></div></div><script>//要取得得属性// name price--toFixed(2)保留两位小数 picture count spec--需要进行解构处理// const goodsList = [{id: '4001172',name: '称心如意手摇咖啡磨豆机咖啡豆研磨机',price: 289.9,picture: 'https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg',count: 2,spec: { color: '白色' }},{id: '4001009',name: '竹制干泡茶盘正方形沥水茶台品茶盘',price: 109.8,picture: 'https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png',count: 3,spec: { size: '40cm*40cm', color: '黑色' }},{id: '4001874',name: '古法温酒汝瓷酒具套装白酒杯莲花温酒器',price: 488,picture: 'https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png',count: 1,spec: { color: '青色', sum: '一大四小' }},{id: '4001649',name: '大师监制龙泉青瓷茶叶罐',price: 139,picture: 'https://yanxuan-item.nosdn.127.net/4356c9fc150753775fe56b465314f1eb.png',count: 1,spec: { size: '小号', color: '紫色' },gift: '50g茶叶,清洗球'}]//1.获取数据,对一些需要的数据进行解构和变换let str = ``;goodsList.forEach(goods => {const { name, price, picture, count, spec, gift } = goods;const price1 = price.toFixed(2);const whatStr = Object.values(spec).join('/');let giftArr;if (gift !== undefined) {giftArr = gift.split(',');}const countPrice = (price1 * count).toFixed(2);if (gift !== undefined) {str += `<div class="item"><img src="${picture}" alt=""><p class="name">${name}`giftArr.forEach(item => {str += `<span class="tag">【赠品】${item}</span>`})str += `<p class="spec">${whatStr}</p><p class="price">${price1}</p><p class="count">x${count}</p><p class="sub-total">${countPrice}</p></div>`} else {str += `<div class="item"><img src="${picture}" alt=""><p class="name">${name}</p><p class="spec">${whatStr}</p><p class="price">${price1}</p><p class="count">x${count}</p><p class="sub-total">${countPrice}</p></div>`}})//计算合计的价格const allMoney = goodsList.reduce((pre, item) => pre + (item.price * 100 * item.count) / 100, 0).toFixed(2);//2.将数据渲染到页面中const list = document.querySelector('.list').innerHTML = str;const total = document.querySelector('.amount').innerHTML = allMoney;</script>
</body></html>

展示效果:

在这里插入图片描述

http://www.lryc.cn/news/459188.html

相关文章:

  • 网络爬虫自动化Selenium模拟用户操作
  • 尚硅谷rabbitmq 2024 流式队列2024指定偏移量 第55节答疑
  • NSSCTF-WEB-pklovecloud
  • 深入Postman- 自动化篇
  • react-JSX
  • 深度对比:IPguard与Ping32在企业网络管理中的应用
  • AI测试之 TestGPT
  • JavaEE-进程与线程
  • JAVA软开-面试经典问题(6)-equals与hashcode方法
  • 计算机网络(以Linux讲解)
  • 计算机网络基本架构知识点
  • GES DISC 的 ATMOS L2 潜在温度网格上的痕量气体,固定场格式 V3 (ATMOSL2TF)
  • MLCC贴片电容不同材质区别:【及电容工作原理】
  • Word粘贴时出现“文件未找到:MathPage.WLL”的解决方案
  • 前端开发笔记--html 黑马程序员1
  • ARM/Linux嵌入式面经(四四):华星光电
  • 帮助,有奖提问
  • Java编辑工具IDEA
  • 闲谈Promise
  • 【C++堆(优先队列)】1882. 使用服务器处理任务|1979
  • VBA高级应用30例应用3Excel中的ListObject对象:选择表的一部分
  • C语言-变量
  • linux下位机出现使用TCP socket为0的问题
  • 论文笔记:Prototypical Verbalizer for Prompt-based Few-shot Tuning
  • nn.functional.softmax(X, dim=-1)
  • 【动态规划】子数组系列(上)
  • 字节青训营入门算法题:飞行棋分组
  • # 执行 rpm -qa | grep qq 查询软件安装情况时报错 数据库损坏 db3 error(-30974)
  • 离线服务器上复现G3SR论文实验
  • Android 未来可能支持 Linux 应用,Linux 终端可能登陆 Android 平台