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

JS进阶(二):创建对象的方式、构造函数、实例成员静态成员、内置构造函数(Object、Array、String、Number)

1、深入对象

1)创建对象三种方式
(1)利用对象字面量创建对象
    const obj = {name: 'lily'}
(2)利用new Object创建对象

        new关键字调用函数的行为被称为实例化。

    // 空对象// const obj = new Object()// obj.name = 'lily'const obj = new Object({ name: 'lily' })
(3)利用构造函数创建对象
  <script>function hs(name, age, gender) {//this.属性名 = 形参this.name = namethis.age = agethis.gender = gender}const into = new hs('lili', 18, 女)</script>
2)构造函数

new实例化执行过程

        只要加了new,自动创建新的对象,此时我们构造的函数中的this指向新对象(new的对象),从而根据 this.属性值 = 形参 添加新的属性,最后返回新的对象。

3)实例成员&静态成员
(1)实例成员

        实例对象是相互独立的,实例成员只能当前实例对象使用

  <script>function hs(name) {//this.属性名 = 形参this.name = name}const into1 = new hs('lili')const into2 = new hs('lily')console.log(into1)  // {name: 'lili'}console.log(into2)  // {name: 'lily'}into1.name = 'lilili' // 实例属性 属于 实例成员console.log(into1)  // {name: 'lilili'}console.log(into2)  //{name: 'lily'}into1.sy = () => {  // 实例方法 属于 实例成员console.log('hello~');}// 新增在实例对象上的方法不影响into2console.log(into1)  // {name: 'lilili', sy: ƒ}console.log(into2)  // {name: 'lily'}console.log(into1 === into2)</script>
(2)静态成员

        静态成员只能通过构造函数访问

  <script>function hs(name) {//this.属性名 = 形参this.name = name}hs.gender = '女'  // 静态属性console.log(hs.gender)  // 女 // 静态方法hs.sy = function () { // 此处不用箭头函数,因为箭头函数没有thisconsole.log(this)}hs.sy()</script>

2、内置构造函数

         函数的使用方法可以在MDN中查找:MDN文档

1)基本包装类型

1)Object

三个常用的静态方法

  <script>const o = { name: 'lily', age: 18 }// 获得所有的属性名console.log(Object.keys(o)) // ['name', 'age']// 获得所有的属性值console.log(Object.values(o)) // ['lily', 18]// 对象的拷贝// const oo = {}// Object.assign(oo, o)  // Object.assign(空对象, 被拷贝的)// console.log(o)  // {name: 'lily', age: 18}Object.assign(o, { gender: '女' })console.log(o)  // {name: 'lily', age: 18, gender: '女'}</script>
2)Array

(1)数组常见实例方法

(2)reduce

<!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 arr = [1, 3, 4, 6, 8, 9]// 没有初值const getSum = arr.reduce(function (prev, current) {return prev + current// 上一次值    当前值    返回值  (第一次循环)//   1          3         4// 上一次值    当前值    返回值  (第二次循环)//   4          4         8// 上一次值    当前值    返回值  (第三次循环)//   8          6         14// ... ...})console.log(getSum) // 31// 有初始值const total = arr.reduce((prev, current) => prev + current, 10)// 上一次值    当前值    返回值  (第一次循环)//   10          1        11// 上一次值    当前值    返回值  (第二次循环)//   11          3         14// 上一次值    当前值    返回值  (第三次循环)//   14          4         18  // ... ...console.log(total)  // 41</script>
</body></html>

计算薪资
  <script>const arr = [{name: '张三',salary: 10000}, {name: '李四',salary: 10000}, {name: '王五',salary: 10000}]// 如果是数组对象,一定要加初始值0,这样prev就是数字了// const total = arr.reduce((prev, current) => prev + current.salary, 0)// console.log(total)// 每个人涨薪 30% 算总薪资// 如果是数组对象,一定要加初始值0,这样prev就是数字了const total = arr.reduce((prev, current) => prev + current.salary * 1.3, 0)console.log(total)</script>
(3)数组常见方法 - 其他方法

  <script>const arr = [{name: '张三',salary: 10000}, {name: '李四',salary: 10000}, {name: '王五',salary: 10000}]// find 最大用途// 找李四 这个对象,并且返回这个对象const li = arr.find(item => item.name === '李四')console.log(li) // {name: '李四', salary: 10000}// every 检测每一个是否都符合条件,如果都符合返回true,否则返回falseconst arr1 = [1, 2, 3]const flag = arr1.every(item => item >= 0)console.log(flag)//some检测是否符合条件,如果至少有一个符合返回true,否则返回falseconst flag1 = arr1.some(item => item >= 2)console.log(flag1)</script>
小案例
<body><div></div><script>const arr = {name: '张三',salary: 10000}// // const arr1 = Object.values(arr)// console.log(arr1) // 数组// 转换为字符串document.querySelector('div').innerHTML = Object.values(arr).join('/')</script>
</body>
(4)数组常见方法 - 伪数组转换为真数组

        静态方法:Array.from( )

<body><ul><li>1</li><li>2</li><li>3</li></ul><script>const lis = document.querySelectorAll('ul li')console.log(lis)  // 伪数组const lis1 = Array.from(lis)console.log(lis1) // [li, li, li]lis1.pop()console.log(lis1) // [li, li]</script>
</body>
3)String
常见实例方法

  <script>// split 把字符串转换为数组   和 join() 相反const str = '2025/10/10'const arr = str.split('/')console.log(arr)  // ['2025', '10', '10']const str1 = '2025-10-10'const arr1 = str1.split('-')console.log(arr1)  // ['2025', '10', '10']// substring(开始的索引号[, 结束的索引号]) 字符串截取 返回值:包含给定字符串的指定部分的新字符串// [ 开始的索引号, 结束的索引号 ) 左闭右开const str2 = 'abcdefghijk'// 省略结束的索引号 截取的字符串为从开始的索引号到结尾console.log(str2.substring(5))  // fghijkconsole.log(str2.substring(0, 6))  // abcdefconsole.log(str2.substring(6, 10))  // ghij// startsWith 检测当前字符串是否以某字符开头 返回值是布尔型// startsWith(检测字符串[, 开始位置(默认值0)])const str3 = 'a b c defghijk'console.log(str3.startsWith('def'))  // falseconsole.log(str3.startsWith('a b'))  // trueconsole.log(str3.startsWith('def', 6))  // true// includes(搜索的字符串[, 检测位置索引号]) 判断一个字符串是否包含在另一个字符串中 ,根据情况返回 true or false// includes() 方法区分大小写const str4 = 'abcdefgh'console.log(str4.includes('def')) //trueconsole.log(str4.includes('bcd', 2)) //false</script>
显示赠品练习

<body><div></div><script>const gift = '50g的茶叶,清洗球'// 把字符串拆分为数组console.log(gift.split(','))// 根据数组元素的个数,生成对应 span标签document.querySelector('div').innerHTML = gift.split(',').map(item => `<span>【赠品】 ${item}</span><br>`).join('')</script>
</body>
4)Number

  <script>const num1 = 10.111const num2 = 1console.log(num1.toFixed(2))  // 10.11console.log(num2.toFixed(2))  // 1.00</script>

3、案例:购物车

<!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;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>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茶叶,清洗球'}]document.querySelector('div').innerHTML = goodsList.map(item => {console.log(item) // 每一条数据// 对象解构const { picture, name, price, count, spec, gift } = itemconst text = Object.values(spec).join('/')const str = gift ? gift.split(',').map(item => `<span class="tag">【赠品】${item}</span> `).join('') : ''// 注意精度问题const subTotal = ((price * count * 100)) / 100return `<div class="item"><img src=${picture} alt=""><p class="name">${name} ${str}</p><p class="spec">${text}</p><p class="price">${price.toFixed(2)}</p><p class="count">x${count}</p><p class="sub-total">${subTotal.toFixed(2)}</p></div>
`}).join('')const total = goodsList.reduce((prev, item) => prev + (item.price * item.count * 100) / 100, 0)document.querySelector('.amount').innerHTML = total.toFixed(2)</script>
</body></html>
http://www.dtcms.com/a/466352.html

相关文章:

  • 半监督学习:机器学习中的“半指导”学习范式
  • 广州网站建设 八爪鱼高层网络架构
  • [SIGCOMM‘25] Revisiting RDMA Reliability for Lossy Fabrics
  • Liunx入门(复习哈哈哈)
  • 南山区做网站公司h5商城网站是什么意思
  • 过拟合:机器学习中的“记忆“与“理解“之战
  • 网站有哪些类型和它的成功案例网站建设客户常见问题集锦
  • 贝叶斯压缩:智能模型压缩与不确定性管理的艺术
  • 【医学影像 AI】基于对抗学习的多层次密集传输知识蒸馏用于AP-ROP检测
  • Elasticsearch 7.12 图形化界面配置(亲测)
  • 将你的Django/Flask应用部署到云服务器(Docker实战)
  • 免费建站网站一级123456便宜做网站价格
  • 长阳网站建设十大邮箱app排行榜
  • 在网站中加入锚链接应该怎么做深圳做网站 信科网络
  • 德州市住房和城乡建设部网站百度如何推广产品
  • 收录查询 站长工具可以做渗透的网站
  • Unity2022Navigation系统打开方式
  • Python 循环详解:while 循环与 for 循环
  • 朝阳凌源网站建设南通做网站的
  • 网络层协议之IP协议
  • 易语言做网站登陆wordpress 整合论坛
  • 软件承接网站建设做儿童文学的网站
  • 视频字幕去除实用方法,轻松解决观看干扰问题
  • 大同市住房与城乡建设厅网站vuejs 网站开发
  • MySQL——数据库操作攻略
  • 记录一下在微信小程序中的使用MobX做状态管理
  • 如何用flashfxp上传网站防水网站的外链如何找
  • 网站seo计划.net 网站关键字
  • 7个免费的ui素材网站wordpress分类目录id
  • 小璇seo优化网站策划推广活动方案