Nur*_*ony 55 javascript variadic-functions ecmascript-6 spread-syntax
我对ES2015中的spread语法和rest参数感到困惑.任何人都能用适当的例子来解释它们之间的区别吗?
TbW*_*321 112
使用spread时,您将单个变量扩展为更多:
var abc = ['a', 'b', 'c'];
var def = ['d', 'e', 'f'];
var alpha = [ ...abc, ...def ];
console.log(alpha)// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];Run Code Online (Sandbox Code Playgroud)
使用rest参数时,您将函数的所有剩余参数折叠为一个数组:
function sum( first, ...others ) {
for ( var i = 0; i < others.length; i++ )
first += others[i];
return first;
}
console.log(sum(1,2,3,4))// sum(1, 2, 3, 4) == 10;Run Code Online (Sandbox Code Playgroud)
Man*_*z90 61
ES6具有三个点的新功能 ...
以下是我们如何使用这些点:
作为休息/收集/收集
var [c, ...m] = [1,2,3,4,5]; // m -> [2,3,4,5]
Run Code Online (Sandbox Code Playgroud)
这...m是一个收集器,它收集其余的参数.在我们内写的时候:
var [c, ...m] = [1,2,3,4,5];
JavaScript确实如下
var c = 1,
m = [2, 3, 4, 5];
Run Code Online (Sandbox Code Playgroud)
作为传播
var params = [ "hello", true, 7 ];
var other = [ 1, 2, ...params ]; // other => [1,2,"hello", true, 7]
Run Code Online (Sandbox Code Playgroud)
在这里,...params传播以便将其所有元素分配给other
内部javaScript确实如下
var other = [1, 2].concat(params);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
在javascript ...中超载。它根据使用运算符的位置执行不同的操作:
其余参数语法:
function rest(first, second, ...remainder) {
console.log(remainder);
}
// 3, 4 ,5 are the remaining parameters and will be
// merged together in to an array called remainder
rest(1, 2, 3, 4, 5);Run Code Online (Sandbox Code Playgroud)
传播语法:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
// the numbers array will be spread over the
// x y z parameters in the sum function
console.log(sum(...numbers));
// the numbers array is spread out in the array literal
// before the elements 4 and 5 are added
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);Run Code Online (Sandbox Code Playgroud)
小智 7
Javascript 的三点 ( ...) 运算符可以以两种不同的方式使用:
var days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"];
const [sat, sun, ...weekdays] = days;
console.log(sat); // "Sat"
console.log(sun); // "Sun"
console.log(weekdays); // ["Mon", "Tue", "Wed", "Thu", "Fri"]Run Code Online (Sandbox Code Playgroud)
var weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
var days = [...weekdays, "Sat", "Sun"];
console.log(days) // ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]Run Code Online (Sandbox Code Playgroud)
请注意,展开运算符可以是第一个元素,但剩余参数需要是最后一个以收集其余元素。