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

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

问题描述

我遇到新的 Array.of ()是在ES6已经定稿,我在想,当一个人可能使用的方法:

  VAR一个= Array.of('富','棒');

 变种B = ['富','酒吧'],
    C =新的Array('富','棒');


解决方案

实例与多家数组创建一个具有多个插槽的数组。

 新阵列(2);
> [未定义×2]

实例使用 Array.of 创建了这些元素的数组。

  Array.of(2)
> [2]

的点 Array.of 是要解决要绕过这被后来建造,这在阵列的特殊情况是有问题的,当一个类型的问题它接收一个参数。例如:

 功能版本(myItem,ARG){
  返回新myItem(ARG);
}

这将使:

 的console.log(建(阵列,2));
> [未定义×2]
//?无法通过字面定义:
//console.log(建([,1))
的console.log(建(Array.of,2));
> [2]

或者用更ES6为例:

  VAR PARAMS = [2,3];
的console.log(新阵列(... PARAMS));
// [2,3]
的console.log(新Array.of(... PARAMS));
// [2,3]
PARAMS = [2];
的console.log(新阵列(... PARAMS));
// [未定义X2]
的console.log(新Array.of(... PARAMS));
// [2]

Array.of 始终做你所期望的。

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');

over:

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]

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

Array.of(2)
> [2]

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);
}

Which would give:

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]

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 consistently does what you expect.

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

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