在阵列填充初始化的阵列上使用阵列映射的意外行为 [英] Unexpected behavior using Array Map on an Array Initialized with Array Fill

查看:84
本文介绍了在阵列填充初始化的阵列上使用阵列映射的意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在使用 Array.prototype时出现意外输出,我遇到了新的 Array.prototype.fill 方法的问题。图。例如:

I've ran into an issue with the new Array.prototype.fill method due to unexpected output when using it with Array.prototype.map. For example:

// Initialize our n x n matrix and fill with 0's
let M = Array(3).fill(Array(3).fill(0));

M.map(function (row, i) {
    row[i] = i;
    return row;
}); //=> [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

在上面的示例中,我希望输出与以下示例相同:

In the above example, I expect the output to be the same as the below example:

let  M = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];

M.map(function (row, i) {
    row[i] = i;
    return row;
}); //=> [[0, 0, 0], [0, 1, 0], [0, 0, 2]]

但是不是。由于某些原因,在第一个示例中返回的结果在下一次迭代中被用作行值。有什么想法可能会发生?我正在使用6to5ify转换来浏览,以将ES6代码转换为ES5。

However it isn't. For some reason the result being returned in the first example is being used as the row value in the next iteration. Any ideas why this might be occuring? I'm using the 6to5ify transform for browserify to transform the ES6 code to ES5.

推荐答案

您的代码相当于: p>

Your code is equivalent to:

let inner = Array(3).fill(0);
let M = Array(3).fill(inner);

当您通过 inner .fill(),它不会复制它, M 数组包含对同一个数组的3个引用。所以对于 M 的一个元素,你所做的任何事情都会发生在这些。

When you pass inner to .fill(), it doesn't make copies of it, the M array contains 3 references to the same array. So anything you do to one element of M happens to them all.

你需要为每个元素 M

let M = [];
for (var i = 0; i < 3; i++) {
    M.push(Array(3).fill(0));
}

这篇关于在阵列填充初始化的阵列上使用阵列映射的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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