什么是“......”数组中的(三点)表示法是什么意思?
问题描述:
我不明白 ...
符号究竟是什么。
I don't understand what the ...
notation does exactly.
我尝试了一个简单的例子用Babel来理解它( 查看示例 ),但似乎:
I tried a simple example with Babel to understand it (view the example), but it seems that:
ES6语法
let myArray = [1, 2, 3, ...18];
console.log(myArray); // [1, 2, 3]
console.log(myArray[4]);// undefined
console.log(myArray.length); // 3
与此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
但是:此代码的作用是什么?因为输出( console.log
)与此代码(ES5)相同:
BUT: What does this code do? Because the output (console.log
) is the same as in this code (ES5):
var myArray = [1,2,3];
console.log(myArray); // [1, 2, 3]
console.log(myArray[4]);// undefined
console.log(myArray.length); // 3
... 18 $ c $是什么c>符号是什么意思?
答
...
( 传播运营商 )的工作原理通过将索引 0
中的每个值返回到索引 length-1
:
The ...
(spread operator) works by returning each value from index 0
to index length-1
:
例如:
[...'18'] // returns ['1', '8']
与以下内容相同:
['18'[0], '18'[1]]
现在,从 1
获取一个数组到 18
,你可以这样做:
Now, to get an array from 1
to 18
, you can do this:
[...Array(19).keys()].slice(1)
或者这个地图:
[...Array(18)].map(_=>i++,i=1)
希望它有所帮助。