new Array(_)。fill(object)不创建新的对象实例 [英] new Array(_).fill(object) does not create new instances of object

查看:225
本文介绍了new Array(_)。fill(object)不创建新的对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6允许我们填写一个数组,具有一定的值:

ES6 allows us to fill an Array with a certain value:

function emptyRow() {
    return new Array(9).fill(0);
}

此函数返回一个 Array 仅填充零:

This function returns an Array of length 9, filled with only zeros:

>> emptyRow()
<< Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

我想生成一个数组,填充了这些空行中的九个。

Now I want to generate an Array that is filled with nine of those empty rows.

function emptyMatrix() {
    return new Array(9).fill(emptyRow());
}

但是,而不是 fill 调用 emptyRow()九次,似乎称之为一次,并将九个引用填充到新的数组 emptyRow()创建的对象。当然,如果我在任何一个子数组中更改一个值,则所有子数组的值都将以相同的索引进行更改。

However, instead of fill calling emptyRow() nine times, it seems to call it once and fills the new Array with nine references to the object created by emptyRow(). Naturally, if I change a value within any of those sub-arrays, the value is changed at the same index for all sub-arrays.

有没有办法创建每个条目的一个新对象?

Is there a way to create a new object for each entry?

推荐答案

Array#fill won' t帮助你,它接受 emptyRow()返回的值,这个已经创建的对象。您可以使用接受函数的 Array#map ,尽管您将无法使用新的Array()构造函数。这是最简单的方法:

Array#fill won't help you, it accepts the value returned by emptyRow(), the already created object. You could use Array#map which accepts a function, although you won't be able to use the new Array() constructor. Here's the simplest way:

function emptyMatrix() {
  Array.apply(null, {length: 9}).map(emptyRow);
  // create the array            fill in values
}

或者,更一般:

function generateArray(n, valueFactory) {
  return Array.apply(null, {length: n}).map(valueFactory);
}

这篇关于new Array(_)。fill(object)不创建新的对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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