ES6的解构赋值

解构赋值
解构赋值主要分为对象的解构和数组的解构,解构赋值,简单理解就是等号的左边和右边相等。
字符串的解构赋值

const str = "I am the bone of my sword"; //
const [a, b, c, ...oth] = str;
console.log(a);     // "I"
console.log(b);     // " "
console.log(c);     // "a"
console.log(oth);   // ["m", " ", "t", "h", "e", " ", "b", "o", "n", "e", " ", 
                    // "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]

// 以下三个的结果是一样的
const [...spStr1] = str;
const spStr2 = str.split("");
const spStr3 = [...str];

console.log(spStr1); // ["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n", 
                     // "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
console.log(spStr2); // ["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n", 
                     // "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]
console.log(spStr3); // ["I", " ", "a", "m", " ", "t", "h", "e", " ", "b", "o", "n", 
                     // "e", " ", "o", "f", " ", "m", "y", " ", "s", "w", "o", "r", "d"]

数组中的解构赋值
语法:let [a,b,c] = [1,2,3] (把右边的值对应下表赋值给左边的变量)

let arr = [0,1,2]
let [a,b,c] = arr
console.log(a) // 0
console.log(b) // 1
console.log(c) // 2

默认值

// 只有当值是undefined的时候才会使用默认值,即使值是null也不会使用默认值
const arr = [1, undefined, undefined, null];
const [a, b = 2, c, d = "aaa"] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // undefined
console.log(d); // null

交换变量

// 不需要中间变量
let a = 20;
let b = 10;

[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 20

对象的解构赋值
语法:let { a, b } = { a: ‘aaa’, b: ‘bbb’ };(以变量与key对应赋值)
对象的解构赋值和数组的解构赋值其实类似,但是数组的数组成员是有序的
而对象的属性则是无序的,所以对象的解构赋值简单理解是等号的左边和右边的结构相同

// 使用对象的结构赋值是,属性名必须跟解构对象的属性名一致
// 因为对象与数组不同,对象是无序的,只能通过属性名来标识
const xiaoming = {
    name: "小明",
    age: 10
};
const { name, age } = xiaoming;
console.log(name);  // 小明
console.log(age);   // 10

默认值

// 默认值
let girlfriend = {
    name: "小红"
};
let { name, age = 24, hobby = ["学习"] } = girlfriend;
console.log(name);  // 小红
console.log(age);   // 24
console.log(hobby); // ["学习"]

函数参数的解构赋值
语法:[[1, 2], [3, 4]].map(([a, b]) => a + b); \ [3, 7]

function fn({
    a,
    b,
    c = 10,
    d = 20,
} = {}){
    return a+b+c+d;
}

fn({a:1,b:2})
// 33

函数参数的默认值

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值