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

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

问题描述

我不明白 ... 符号究竟是什么。

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

推荐答案

... 传播运营商 )的工作原理通过将索引 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)

希望它有所帮助。

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

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