Blogger Information
Blog 94
fans 0
comment 0
visits 92732
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】JS之解构赋值
可乐随笔
Original
638 people have browsed it

解构赋值

传统写法

  1. const data = [100, 200]
  2. let a = data[0]
  3. let b = data[1]
  4. console.log(a, b)
  5. console.log('--------------------')

解构语法

  1. // * 模板 = 集合(数组,对象)
  2. // ! 数组
  3. let [uname, email] = ['老马', 'nx99@qq.com']
  4. console.log(uname, email);
  5. // 更新数据
  6. // 在 [],{},() 之前的分号; 不能省
  7. ;[uname, email] = ['老王', 'nx88@qq.com']
  8. console.log(uname, email)
  9. console.log('--------------------');
  10. // 1.参数少于值数量, 多出的参数给默认值
  11. ;[uname, email, gender = '女'] = ['老李', 'nx66@qq.com']
  12. console.log(uname, email, gender);
  13. // 2. 参数少于值数量,...rest
  14. ;[uname, ...arr] = ['老刘', 'nx55@qq.com', '女']
  15. console.log(uname, arr) //多余的数压缩到了arr数组中
  16. console.log(uname, ...arr) //展开arr数组
  17. console.log('--------------------');

应用场景1:交换二个数

  1. let x = 10
  2. let y = 20
  3. console.log(`x = ${x}, y = ${y}`);
  4. ;[x, y] = [y, x]
  5. console.log(`x = ${x}, y = ${y}`)
  6. console.log('--------------------');

应用场景2:对象解构

  1. // ? 变量名 === 属性名
  2. let { num, price } = { num: 2, price: 5000 }
  3. console.log(num, price)
  4. // []{}()之前分号不能省略
  5. //{}不能出现在等号左边(左值),所以要加上括号()转成表达式
  6. ; ({ num, price } = { num: 5, price: 6000 })
  7. console.log(num, price)
  8. // 命名冲突,别名
  9. let { pname, price: uniPrice } = { pname: '手机', price: 8000 }
  10. console.log(pname, uniPrice)
  11. console.log('--------------------');

应用场景3:克隆对象

  1. let lesson = { name: 'ES6', scroe: 80 }
  2. console.log(lesson)
  3. //如果想创建二个不相关的对象,值又一样,只能克隆
  4. let { ...obj } = lesson
  5. console.log(obj)
  6. console.log(obj === lesson)
  7. console.log('--------------------');

应用场景4:解构传参

  1. let show = function (user) {
  2. //user是一个对象
  3. return `${user.uname}: (${user.email})`
  4. }
  5. let user = { uname: '老马', email: 'nx99@qq.com' }
  6. console.log(show(user))
  7. // 简化,使用对象解构方法传参
  8. show = function ({uname,email}) {
  9. //user是一个对象
  10. return `${uname}: (${email})`
  11. }
  12. user = { uname: '老李', email: 'nx88@qq.com' }
  13. console.log(show(user))
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post