【ES6 对象的解构赋值】数组 对象 其他

**基本原则如下:

https://editor.csdn.net/md?not_checkout=1&articleId=121850521
数组的元素是按次序排列的,变量的取值由它的位置决定;
对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

数组的解构赋值:

let [x, y]= [1, 2];
// x = 1
// y = 2

对象的解构赋值:

let { foo , bar } = { foo: "aaa", bar: "bbb" };
// foo = "aaa"
// bar = "bbb"

但是对象的解构赋值,允许给赋值的变量重命名。

交换变量的值

let x = 1;
let y = 2;
[x, y] = [y, x];

从函数返回多个值

// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
 
// 返回一个对象
function example() {
return {
 foo: 1,
 bar: 2
};
}
let { foo, bar } = example();


函数参数的默认值

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
}) {
  // ... do stuff
};

遍历Map结构

var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
 
for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

es5一次声明多个变量

var a = 1,
    b = 2,
    c = 3,
    ...;
1
2
3
4

es6一次声明多个变量

let [a,b,c] = [1,2,3];
//a = 1
//b = 2
//c = 3

数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined

如果变量名与属性名不一致,必须写成下面这样。

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"

let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'

类似数组的对象都有一个length属性,还可以对这个属性解构赋值。

let {length : len} = 'hello';
len // 5

对象数组嵌套

let obj={ a1:[ 1, 2, 3], a2: '123'}
//x=obj.a1[0]
//y=obj.a1[1]
let { a2, a1:[ x, y]}= obj
console. log( a2, x, y) //'123' 1 2


let obj1={ s:{ n: '1'}, n:[ 1, '2', 3, '4'], m:[[ 1]]}
let { m:[ x1], s:{ n}, n:[,... m2]}= obj1

console. log( x1, n, m2) // [1] '1' ['2',3,'4']

-用途

  1. 除了可以一次定义多个变量
  2. 还可以让函数返回多个值
  3. 可以方便地让函数的参数跟值对应起来
  4. 提取json数据
  5. 函数参数的默认值

https://editor.csdn.net/md?not_checkout=1&articleId=121850521

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值