Javascript(ES6)Array.of()的用例是什么?

时间:2015-07-28 20:24:29

标签: javascript arrays ecmascript-6

我遇到了在ES6中最终确定的新Array.of()方法,我想知道何时可以使用:

HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

在:

var a = Array.of('foo', 'bar');

4 个答案:

答案 0 :(得分:10)

使用数字实例化数组会创建一个包含许多插槽的数组。

new Array(2);
> [undefined x 2]

使用Array.of进行实例化会创建一个包含这些元素的数组。

Array.of(2)
> [2]

Array.of的要点是解决你想要传递后来构造的类型的问题,在数组的特殊情况下,当它收到一个参数时会出现问题。例如:

function build(myItem, arg){
  return new myItem(arg);
}

哪会给:

console.log(build(Array, 2));
> [undefined x 2]
// ??? Can't pass the literal definition:
//console.log(build([, 1))
console.log(build(Array.of, 2));
> [2]

或者使用更多的ES6作为例子:

var params = [2,3];
console.log(new Array(...params));
// [2,3]
console.log(new Array.of(...params));
// [2,3]
params = [2];
console.log(new Array(...params));
// [undefined x2]
console.log(new Array.of(...params));
// [2]

Array.of始终如一地满足您的期望。

答案 1 :(得分:2)

我用Google搜索了它,the first result有一个很好的例子:

  

Array.of(...项目)

     

如果要将多个值转换为数组,则应始终使用   使用数组文字,特别是因为数组构造函数没有   如果只有一个数字(这个怪癖上为more information),则可以正常工作:

new Array(3, 11, 8)
// => [ 3, 11, 8 ]
new Array(3)
// => [ , ,  ,]
new Array(3.1)
// => RangeError: Invalid array length
     

但是你应该如何将值转换为a的实例   那么Array的子​​构造函数呢?这是Array.of()帮助的地方   (请记住,Array的子​​构造函数继承了所有的Array   方法,包括of())。

class MyArray extends Array {
    ...
}
console.log(MyArray.of(3, 11, 8) instanceof MyArray); // true
console.log(MyArray.of(3).length === 1); // true

值得注意的是,Array.of()还保留了Array与TypedArray的API兼容性。使用TypedArray(Int32Array,UInt32Array等),of()非常有用。来自MDN

Uint8Array.of(1);            // Uint8Array [ 1 ]
Int8Array.of("1", "2", "3"); // Int8Array [ 1, 2, 3 ]
Float32Array.of(1, 2, 3);    // Float32Array [ 1, 2, 3 ]
Int16Array.of(undefined);    // IntArray [ 0 ]

答案 2 :(得分:1)

它基本上修复了Array构造函数,当你传递一个数字时,它有一个特例。

来自original proposal

  

Array.of提供了一个与Array不同的构造函数   new Array(42)的特殊情况,预设length(和   提示实现预分配)但在[0, length)中留下了漏洞。

     

用例是当你不能写一个文字,因为你传递的函数 - 构造为funarg,并且最终   调用者只能传递一个数字arg或几个args。

它也有助于子类化,它可以用作数组子类实例的“文字形式”。

答案 3 :(得分:0)

Array.of([elem1], [elem2], ...)

在数组中返回elem1, elem2,等。

相当于:

Array.of = function() {
    return [].slice.call( arguments );
};

示例:

 Array.of("red", "green", "blue")

    [ 'red', 'green', 'blue' ]

当您需要构造函数(例如将其传递给另一个函数)的数组时,此方法很有用。该方法可以避免Array构造函数的潜在缺陷:如果它有多个参数,它的行为类似于数组文字。如果它有一个参数,它会创建一个给定长度的空数组。

 new Array(3, 4, 5)
    [ 3, 4, 5 ]
    new Array(3)
    []

这是在ECMAScript中添加的link到六个新的数组方法,以供进一步参考。

相关问题