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

Ale*_*oss 3 javascript arrays ecmascript-6

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

var a = Array.of('foo', 'bar');
Run Code Online (Sandbox Code Playgroud)

过度:

var b = ['foo', 'bar'],
    c = new Array('foo', 'bar');
Run Code Online (Sandbox Code Playgroud)

Kit*_*nde 10

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

new Array(2);
> [undefined x 2]
Run Code Online (Sandbox Code Playgroud)

实例化使用Array.of创建具有这些元素的数组.

Array.of(2)
> [2]
Run Code Online (Sandbox Code Playgroud)

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

function build(myItem, arg){
  return new myItem(arg);
}
Run Code Online (Sandbox Code Playgroud)

哪个会给:

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]
Run Code Online (Sandbox Code Playgroud)

或者以更多的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]
Run Code Online (Sandbox Code Playgroud)

Array.of 始终按照您的期望行事.