[英]All three if statements in a for loop triggering when only one is true (JavaScript)
This has me a little stumped. 这让我有些困惑。 Whenever I execute this code, if one of the
if
statements in the for
loop are true, all three sub-arrays of weaknessArray
get effected. 每当我执行此代码,如果一个
if
语句中for
循环是真实的,所有的三个子阵列weaknessArray
得到实现。 The same thing happens when each if
statement is in it's own for
loop and if instead of one 2D array I use a three separate arrays, one for each for
loop. 当每个
if
语句都在其自己的for
循环中并且if代替一个2D数组而不是一个2D数组时,会发生相同的事情,每个for
循环一个。
var typeChart = [2,2,2,2,2,2,4,2,2,2,2,2,2,0,2,2,2,2];
var blankArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var weaknessArray = [blankArray,blankArray,blankArray];
for(i = 0; i<18; i++){
if(typeChart[i] === 0) weaknessArray[2][i] = 1;
if(typeChart[i] === 1) weaknessArray[1][i] = 1;
if(typeChart[i] === 4) weaknessArray[0][i] = 1;
console.log(weaknessArray);
}
There is only ever one blankArray
object in memory; 内存中只有一个
blankArray
对象; your weaknessArray
contains three references to the same object . 您的
weaknessArray
包含对同一对象的三个引用。
Create copies instead with .slice
, so that you have three arrays (well, four, counting the original) in memory instead of one: 用
.slice
代替创建副本,这样.slice
有三个数组(好吧,四个,计算原始数组),而不是一个:
var typeChart = [2,2,2,2,2,2,4,2,2,2,2,2,2,0,2,2,2,2]; var blankArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; var weaknessArray = [blankArray.slice(), blankArray.slice(), blankArray.slice()]; for(i = 0; i<18; i++){ if(typeChart[i] === 0) weaknessArray[2][i] = 1; if(typeChart[i] === 1) weaknessArray[1][i] = 1; if(typeChart[i] === 4) weaknessArray[0][i] = 1; console.log(weaknessArray); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.