“……"是什么意思?数组中的(三点)符号是什么意思? [英] What does the "..." (triple dot) notation in arrays mean?

查看:53
本文介绍了“……"是什么意思?数组中的(三点)符号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白 ... 符号到底是做什么的.

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 符号是什么意思?

推荐答案

...(spread operator) 的工作原理是将每个值从索引 0 返回到索引 长度-1:

例如:

[...'18'] // returns ['1', '8']

相当于:

['18'[0], '18'[1]]

<小时>

现在,要获取从 118 的数组,您可以这样做:


Now, to get an array from 1 to 18, you can do this:

[...Array(19).keys()].slice(1)

或者这个带地图:

[...Array(18)].map(_=>i++,i=1)

希望有帮助.

这篇关于“……"是什么意思?数组中的(三点)符号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆