Javascript (ES6) Array.of() 的用例是什么? [英] What is the use case for Javascript's (ES6) Array.of()?

查看:30
本文介绍了Javascript (ES6) Array.of() 的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了新的 Array.of() 方法已经在 ES6 中完成,我想知道什么时候可以使用:

I came across the new Array.of() method that's been finalized in ES6, and I was wondering when one might use:

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

结束:

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

推荐答案

用一个数字实例化一个数组会创建一个有那么多槽的数组.

instantiating an Array with a number creates an array with that many slots.

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

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

instantiating using Array.of creates an array with those elements.

Array.of(2)
> [2]

Array.of 的重点是解决您希望传递稍后构造的类型的问题,在数组的特殊情况下,当它接收单个参数时会出现问题.例如:

The point of Array.of is to solve the issue where you want to pass a type around that gets constructed later, which in the special case of array is problematic when it receives a single argument. For instance:

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 为例:

Or to use even more of ES6 as an example:

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 始终如一地满足您的期望.

Array.of consistently does what you expect.

这篇关于Javascript (ES6) Array.of() 的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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