JavaScript ES6 Spread运算符可以用于类似数组的对象吗?

时间:2019-12-16 20:10:13

标签: javascript ecmascript-6 spread-syntax

我发现Spread运算符可以与arguments一起使用:

function foo() {
    [...arr] = arguments;
    console.log(arr, Array.isArray(arr));
}

foo(1, 3, 5);

// note that we could also use function foo(...args) { } to begin with

但不适用于类似数组的对象(它将引发错误TypeError: undefined is not a function):

let obj = { 0: "abc", 1: 3.14, length: 2 };

[...arr] = obj;
console.log(arr, Array.isArray(arr));

那么Spread运算符可以用于类似数组的对象吗?

请注意,以下内容都可以组成一个数组:

let obj = { 0: "abc", 1: 3.14, length: 2 };
let arr = Array.prototype.slice.call(obj);
console.log(arr, Array.isArray(arr));

let arr2 = Array.from(obj);
console.log(arr2, Array.isArray(arr2));

0 个答案:

没有答案