如何使用扩展运算符和 Rest 参数
扩展运算符用三个点号表示,功能是把数组或类数组对象展开成一系列用逗号隔开的值 rest运算符也是三个点号,不过其功能与扩展运算符恰好相反,把

随着 ES6的引入,Javascript 开发人员获得了一些特性。在这篇文章中,我将特别介绍两个特性:
spread operator 扩展运算符
rest parameter Rest参数
扩展操作符
扩展运算符只是三个点,它用在某种类型的迭代(如数组或字符串)之前
当我们想要将数组或字符串扩展或分解成单独的参数或元素时,我们可以使用 spread 操作符,这样我们就可以很容易地在函数或数组中使用它们,因为函数或数组中需要参数或元素
拆解字符串与数组.
js
var array = [1,2,3,4,5];
console.log(...array);//1 2 3 4 5
var str = "String";
console.log(...str);//S t r i n g
将伪数组转化为数组
js
//伪数组转换为数组
var divs = document.getElementsByTagName('div');
console.log([...divs]);//[div, div]
在函数中使用它:
js
function sentence(name, occupation, mood){
return `${name} is a ${occupation}. ${name} is ${mood}`
}
// 普通写法
sentence("vipbic","programmer","tired") // vipbic is a programmer. vipbic is tired.
// apply
let words = ["vipbic","programmer","tired"]
sentence.apply(null, words) // vipbic is a programmer. vipbic is tired.
// ...写法
let words = ["vipbic","programmer","tired"]
sentence(...words) // vipbic is a programmer. vipbic is tired"
在数组中使用
js
let fourFiveSix = [4,5,6]
let numbers = [1,2,3,...fourFiveSix,7]
console.log(numbers) // [1,2,3,4,5,6,7]
Rest参数
Rest parameterrest 参数(仅用作函数中的最后一个参数)允许我们将参数表示为没有限制的数组
为了使用一个 rest 参数ーー我们只需要使用三个点,后面跟着我们想要引用的将要被引用的数组。它本质上与我们的扩展运算符所做的相反,因为它将任意数量的参数组合成一个数组,而通过扩展,扩展,或者将数组的每个元素(或者可选择的迭代元素)分割成它们自己的单个参数/元素
rest 参数的实际使用情况:
js
function numbers(firstNum, secondNum, ...notNumbers){
console.log(firstNum)
console.log(secondNum)
console.log(notNumbers)
}
numbers(1,2,"dog")
// 1
// 2
// ["dog"]
numbers(1,2,"dog","cat",true)
// 1
// 2
// ["dog", "cat", true]
注意,不管我们在前两个参数 firstNum 和 secondNum 之后传递了多少个参数,我们都能够使用额外的参数ーー因为它们被组合成一个数组
扩展 arguments
arguments 有点类似上面的rest参数,但是:arguments 不是数组,所以不能直接使用数组的原生 API 如 forEach,而 Rest Parameter 是数组,可以直接使用数组的原生 API
js
function sum() {
let num = 0
Array.prototype.forEach.call(arguments, function(item) {
num += item * 1
})
return num
}
console.log(sum(1, 2, 3)) // 6
console.log(sum(1, 2, 3, 4)) // 10
js
function sum(...nums) {
let num = 0
nums.forEach(function(item) {
num += item * 1
})
return num
}
console.log(sum(1, 2, 3)) // 6
console.log(sum(1, 2, 3, 4)) // 10
再看两个例子:
js
function foo(x,...args){
console.log(x)
console.log(args)
}
foo(1,2,3)//1 [2,3]
foo(1,2,3,4,5)//1 [2,3,4,5]
js
let [x,...y]=[1,2,3,4,5]
console.log(x)//1
console.log(y)//[2,3,4,5]
最后总结:
扩展运算符用三个点号表示,功能是把数组或类数组对象展开成一系列用逗号隔开的值
rest运算符也是三个点号,不过其功能与扩展运算符恰好相反,把逗号隔开的值序列组合成一个数组
当三个点(...)在等号左边,或者放在形参上。为 rest 运算符
当三个在等号右边,或者放在实参上,是 spread运算符