JavaScript的 - 阵列 - 改变一个元素,但为什么整个柱变了? [英] JavaScript - Array - change one element but why the whole column changed?

查看:70
本文介绍了JavaScript的 - 阵列 - 改变一个元素,但为什么整个柱变了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript的新的,我想初始化一个二维数组,并更改字符中的一个。然而,当我改变数组值之一例如ABC [1,1],整个列改变。我想问一下为什么和如何prevent呢?我曾试图用.slice做一个副本,但似乎不工作

 我的prefered结果
- - -
- 1 -
- - - 实际的答案:
- 1 -
- 1 -
- 1 -
//我的code:
VAR ABC =新的Array(3,3)
为(变量I = 0; I&下; 3;我+ +)
   为(VAR J = 0; J&下; 3; J ++)
      ABC [I,J] = - ABC [1,1] =1为(变量I = 0; I&下; 3;我++){
    为(VAR J = 0; J&下; 3; J ++)
        document.writeln(ABC [I,J] +)
    document.writeln(&所述峰; br \\>中)
}


解决方案

逗号运算计算前两者pressions并返回最后一个。因此, I,J 收益Ĵ

事实上,你正在使用一维数组,而不是二维的。

正确的方法是:

VAR ABC =阵列(3);
为(变量I = 0;我3; ++ⅰ){
   ABC [I] =阵列(3);
   为(VAR J = 0; J&下; 3; ++ j)条
      ABC [I] [J] = -
}
ABC [1] [1] =1;

I am new in JavaScript, I would like to initialize a 2D array and change one of the character. However, when I change one of the array value e.g. abc[1,1], the whole column changed. I would like to ask why and how to prevent it? i have tried to use .slice to make a copy, but seem dont work

My prefered result
- - -
- 1 -
- - -

The actual ans:
- 1 -
- 1 -
- 1 -


//My code:
var abc = new Array(3,3)
for(var i =0; i<3;i++)   
   for(var j =0; j<3;j++)
      abc[i,j]="-"

abc[1,1] ="1"

for(var i =0; i<3;i++){
    for(var j =0; j<3;j++)
        document.writeln(abc[i,j]+" ")
    document.writeln("<br \>")
}

解决方案

The comma operator evaluates both expressions and returns the last one. So i,j returns j.

In fact, you are using a 1D array, not a 2D one.

The proper way is:

var abc = Array(3);
for(var i=0; i<3; ++i) {
   abc[i] = Array(3); 
   for(var j=0; j<3; ++j)
      abc[i][j] = "-"
}
abc[1][1] = "1";

这篇关于JavaScript的 - 阵列 - 改变一个元素,但为什么整个柱变了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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