解构赋值

解构赋值可以从等号右侧的值中提取一个或多个保存到左边的变量中:

let [a, b] = [1, 2] //let a=1, b=2 

通常情况左侧多余的变量会被设置为undefined,右侧多余的变量会被忽略:

let [a, b] = [1] //a==1, y==undefined 右边的值个数比左边少

[a,b] = [1, 2, 3] //a==1, b==2 右边的值个数比左边多,多的丢弃了

 可以通过...把所有没有使用或剩余的值装进一个变量中:

let [a, ...b] = [1, 2, 3, 4] //a==1, b==[2, 3, 4] 这个就是可变参数,相当于python的*参数

 

剩余形参

剩余形参(rest parameter):让我们能够编写出在调用时传入比形参多任意数量的实参的函数。

function max(first=-Infinity, ...rest){

let maxValue = first

for(let n of rest){

if(n > maxValue){

maxValue = n

}

}

return maxValue

}

max(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) //=>10 ,传入的参数数量任意 ,相当于python的*参数

剩余形参的前面有...三个点,且必须是声明中的最后一个。

 

扩展操作符

用于展开数组的元素:(相当于python的解构)

let a = [1, 2, 3]

let b = [0, ...a, 4] //b == [0, 1, 2, 3, 4]

 

复制已有的数组:

let numberCopy = Array.of(...numbers) //numberCopy数组的值复制自numbers数组

 

把字符串转换为单个字符数组:

let nums = [..."123abc"]

nums //=> ["1", "2", "3", "a", "b", "c"]

 

数组去重:把数组转换为集合,再用扩展操作符把集合转换为数组:

let letters = [..."hello world"]

[...new Set(letters)] //=> ["h", "e", "l", "o", " ", "w", "r", "d"]

 

也能用在函数调用中:

let numbers = [5, 2, 10, -1, 9]

Math.min(...numbers) //=> -1

 

REF

https://zhuanlan.zhihu.com/p/434751764

查看原文