Javascript 数组中的“...”(三点)表示法是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36095630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the "..." (triple dot) notation in arrays mean?
提问by Aral Roca
I don't understand what the ...notation does exactly.
我不明白这个...符号到底是做什么的。
I tried a simple example with Babel to understand it (view the example), but it seems that:
我用 Babel 尝试了一个简单的例子来理解它(查看例子),但似乎:
ES6 syntax
ES6 语法
let myArray = [1, 2, 3, ...18];
console.log(myArray); // [1, 2, 3]
console.log(myArray[4]);// undefined
console.log(myArray.length); // 3
is the same as this ES5 syntax:
与此 ES5 语法相同:
"use strict";
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
var myArray = [1, 2, 3].concat(_toConsumableArray(18));
console.log(myArray); // [1, 2, 3]
console.log(myArray[4]); // undefined
console.log(myArray.length); // 3
BUT:What does this code do? Because the output (console.log) is the same as in this code (ES5):
但是:这段代码有什么作用?因为输出 ( console.log) 与此代码 (ES5) 中的相同:
var myArray = [1,2,3];
console.log(myArray); // [1, 2, 3]
console.log(myArray[4]);// undefined
console.log(myArray.length); // 3
What does the ...18notation mean?
什么是...18符号是什么意思?
回答by
The ...(spread operator) works by returning each value from index 0to index length-1:
该...(传播运营商)的工作原理是每个值返回从index0索引length-1:
As example:
例如:
[...'18'] // returns ['1', '8']
which would be the same as:
这将与:
['18'[0], '18'[1]]
Now, to get an array from 1to 18, you can do this:
现在,从得到一个数组1来18,你可以这样做:
[...Array(19).keys()].slice(1)
Or this with map:
或者这与地图:
[...Array(18)].map(_=>i++,i=1)
Hope it helps.
希望能帮助到你。
回答by Alex Booker
The expression [1, 2, 3, ...18]is invalid.
表达式[1, 2, 3, ...18]无效。
You cannot use ...with a Number. You can only use ...with an iterable object like an Array, Stringor Object.
您不能...与Number一起使用。您只能...与可迭代对象一起使用,例如Array、String或Object。
It is interesting to note that Tracur- another transpiler - throws an error when fed the same code:
有趣的是,Tracur——另一个转译器——在输入相同的代码时抛出一个错误:
TypeError: Cannot spread non-iterable object.
类型错误:无法传播不可迭代的对象。
I am not intimate with the specificationbut I think this could be a Babel "bug".
我对规范并不熟悉,但我认为这可能是 Babel 的“错误”。

