Javascript的(ES6)Array.of()有什么用途?

3

我发现了在ES6中最终确定的Array.of()方法,我想知道什么时候可以使用:

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

over:

var b = ['foo', 'bar'],
    c = new Array('foo', 'bar');

我认为它只是添加了一些语法糖。 - Wand Maker
这是更多的括号,不像其他函数那样容易处理,它是糖。 - user985399
4个回答

10
用一个数字实例化一个数组会创建一个具有相应数量插槽的数组。
new Array(2);
> [undefined x 2]

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

Array.of(2)
> [2]
< p > 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]
< p > Array.of 一直做你期望的事情。


2

我为您谷歌了一下,第一个结果有一个很好的例子:

Array.of(...items)

If you want to turn several values into an array, you should always use an array literal, especially since the array constructor doesn’t work properly if there is a single value that is a number (more information on this quirk):

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

But how are you supposed to turn values into an instance of a sub-constructor of Array then? This is where Array.of() helps (remember that sub-constructors of Array inherit all of Array’s methods, including 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() 还保留了与 TypedArray(Int32Array、UInt32Array 等)兼容的 Array API。对于 TypedArray,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 ]

1

这个修复主要是针对Array构造函数,当你传递一个单独的数字时,它有一个特殊情况。

来自原始提案:

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

使用场景是当你不能编写字面量时,因为你正在将一个构造函数作为funarg传递,并且最终调用者可能只传递一个数字参数或多个参数。

它还有助于子类化,其中它可以用作你的数组子类实例的“字面形式”。


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中新增的六种数组方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接