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

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

问题描述

ES6 允许我们用特定值填充 Array:

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

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

这个函数返回一个长度为 9 的 Array,只填充零:

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

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

现在我想生成一个 Array,其中填充了九个空行.

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() 九次,它似乎只调用一次并用九个引用填充新的 Array到由 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 帮不了你,它接受 emptyRow() 返回的值,已经创建的对象.您可以使用接受函数的 Array#map,但您将无法使用 new 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天全站免登陆