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

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

问题描述

我在将新的 Array.prototype.fill 方法与 Array.prototype.map 一起使用时遇到了意外输出问题.例如:

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 转换为 browserify 将 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.

推荐答案

你的代码相当于:

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的每个元素创建新的数组:

You need to make new arrays for each element of M:

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

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

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