其他分享
首页 > 其他分享> > ES6 解构赋值

ES6 解构赋值

作者:互联网

es6对象解构

1.普通使用解构赋值

let obj = {
    name: "fct",
    age: 21
}
// 普通使用解构赋值
var { name, age, hobby } = obj;
console.log(name, age, hobby); //fct 21 undefined

2.对解构赋值重命名

let obj = {
    name: "fct",
    age: 21,
    school: null
}
// 2. 当需要对解构赋值重命名时,新的名字是是后面的
var { name: name1, age, hobby } = obj;
console.log(name1, age, hobby); //fct 21 undefined

3.解构差异

let obj = {
    name: "fct",
    age: 21,
    school: null
}
// 2. 对象更改解构赋值顺序,不会影响值
var { name, hobby, age } = obj;
console.log(name, age, hobby); //fct 21 undefined

// 3.数组解构赋值更改顺序,会影响值
let obj = {
    name: "fct",
    age: 21,
    school: null
}
let arr = [1, 2, 3];
var [a, b, c] = arr;
console.log(a, b, c);   //1 2 3
var [a, c, b] = arr;
console.log(a, b, c);   //1 3 2 

4.解构差异

let obj = {
    name: "fct",
    age: 21,
    school: null
}
// 4.对象解构的默认值
// 默认值想生效,与之对应的属性值一定得是 undefined
var { name: name1, age, hobby = "打游戏", school = "xx大学" } = obj;
console.log(name1, age, hobby, school); //fct 21 打游戏 null

5.检验

// 例题 1:
var { x: y = 5 } = {};
// 要输出 5 ,那么该输出 x,还是 y?
console.log(y); //5

// 例题 2:
var { x: y = 5 } = { x: 3 };
// 输出 y 的值是?
console.log(y); // 3

标签:ES6,fct,name,age,21,解构,obj,赋值
来源: https://www.cnblogs.com/fuct/p/15230360.html