Javascript二维数组:递增特定项的值 [英] Javascript 2-dimensional array: incrementing a specific item's value

查看:105
本文介绍了Javascript二维数组:递增特定项的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有整数的二维数组,而我想要的只是用一个数字递增一个特定的项目。
初始状态:

I have a 2 dimensional array, with integers, and all what I want is to increment a particular item with a number. The initial state:

var arr1=[];
var arr2=[1,2,3];
arr1.push(arr2);
arr1.push(arr2);
arr1.push(arr2);

arr1现在看起来像这样:

arr1 now looks like this:

0:[1, 2, 3]
1:[1, 2, 3]
2:[1, 2, 3]

我想要的是用10增加这个数组的[0,0]元素,所以arr1应该是:

What I want is to increment the [0,0] element of this array with 10, so arr1 should be:

0:[11, 2, 3]
1:[1, 2, 3]
2:[1, 2, 3]

我做了什么:

arr1[0][0]+=10;

但结果如下:

0:[11,2,3]
1:[11,2,3]
2:[11,2,3]

我缺少什么?为什么增加此命令数组元素的位置0处的所有数字?

What am I missing? Why increments this command all the numbers at position 0 of the array elements?

推荐答案

对象(数组也是对象)被传递为引用。这意味着您的数组看起来像这样(伪结构):

Objects (Arrays are Objects too) are passed as references. That means that your array looks like this (pseudostructure):

 arr2 -> [1, 2, 3]
 arr1 -> [ -> arr2, -> arr2 -> arr2]

因此 arr1 [0] 是与 arr1 [1] arr2 相同。要创建三个不同的数组,请复制数组:

Therefore arr1[0] is just the same as arr1[1] or arr2. To create three different arrays copy the array:

 arr1.push([...arr2]);

这篇关于Javascript二维数组:递增特定项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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