解构赋值
解构赋值主要分为对象的解构和数组的解构,解构赋值,简单理解就是等号的左边和右边相等。
字符串的解构赋值
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
};