Array.prototype.fill()从补,因为我去不同 [英] Array.prototype.fill() different from fill as I go

查看:150
本文介绍了Array.prototype.fill()从补,因为我去不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作,其结果输出到一个二维数组的一个问题,增加一到每个元素,因为它去。

I am working on a problem that outputs its results into a 2D array, adding one to each element as it goes.

我简化了code 下尽可能我可以创建一个测试用例。如果我填的是数组作为我走了,如下:

I simplified the code down as far as I could to create a test case. If I fill the array as a I go, as follows:

var a = [[], [], [] ,[] ,[], []];
var d1, d2;
for (d1 = 0; d1 < 6; d1++) {
    for (d2 = 0; d2 < 6; d2++) {
        a[d1][d2] = (a[d1][d2]) ? (a[d1][d2]) + 1 : 1; 
    }
}

我得到一个二维数组,其中所有的值都是1。但是,如果我用array.prototype.fill $ P $数组P灌注()如下:

I get a 2D array where all the values are 1. However, if I prefill the array using array.prototype.fill() as follows:

var a = new Array(6).fill(new Array(6).fill(0));
var d1, d2;
for (d1 = 0; d1 < 6; d1++) {
    for (d2 = 0; d2 < 6; d2++) {
        a[d1][d2] += 1; 
    }
}

我得到一个二维数组满6S的。即使我代替 A [D1] [D2] + = 1 与旧 A [D1] [D2] =(A [D1] [ D2])? (一[D1] [D2])+ 1:1; ,(这应该还是因为这两个0工作和undefined falsy)我仍然得到6S

I get a 2D array full of 6s. Even if I replace a[d1][d2] += 1 with the old a[d1][d2] = (a[d1][d2]) ? (a[d1][d2]) + 1 : 1;, (which should still work since both 0 and undefined are falsy) I still get 6s.

据我所知,我的code应该只是通过每个元素循环,并添加一个到previous值。它不应该接触的任何元素超过一次,所以他们都应该是1秒。不管我填充数组提前或不不应该的问题。

As far as I can tell, my code should just loop through each element and add one to the previous value. It shouldn't touch any element more than once, so they should all be 1s. Whether I fill the array ahead of time or not shouldn't matter.

在哪里是我的理解失败?

Where is the failure in my understanding?

推荐答案

<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\"><$c$c>Array.fill旨在用于填充从开始索引的阵列的所有元素与结束索引的静态的值

这个遗憾,这意味着,如果你在一个元素传递如新阵列,阵列实际上将充满到相同的元素很多引用。换句话说, A 未充满大小六个六个阵列; A 充满六指针的在同一阵列尺寸六

This unfortunately means that if you pass in an element such as a new array, your array will actually be filled with many references to that same element. In other words, a is not filled with six arrays of size six; a is filled with six pointers to the same array of size six.

您可以轻松地在你的开发者控制台验证这一点:

You can easily verify this in your developer console:

var a = new Array(6).fill(new Array(6).fill(0));
a
>>> [Array[6], Array[6], Array[6], Array[6], Array[6], Array[6]]
a[0]
>>> [0, 0, 0, 0, 0, 0]
a[1]
>>> [0, 0, 0, 0, 0, 0]
a[0][1] = 1
a[0]
>>> [0, 1, 0, 0, 0, 0]
a[1]
>>> [0, 1, 0, 0, 0, 0]

这篇关于Array.prototype.fill()从补,因为我去不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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