简体   繁体   English

当只有一个为真时,for循环中的所有三个if语句都会触发(JavaScript)

[英]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.

相关问题 Javascript验证无法正常工作-只要if语句为真,它就会停止所有if语句? - Javascript validation is not working - as soon as one if statement is true, it stops all if statements? Javascript:使用“ if…else”语句触发“ for”循环不起作用 - Javascript: Triggering “for” loop using “if…else” statements not working if陈述式传回true,而不是遍历我所有的if陈述式-JavaScript - if statements returning true and not going over all of my if statements - javascript Javascript:当一个变量为true时,将所有其他变量设置为false - Javascript: when one variable is true, set all other variable to false 学习JavaScript,仅当以下陈述为真时,才打印此行 - Learning JavaScript, how to print out this line only if following statements are true Javascript:比较三个布尔值并返回所有真实的布尔值 - Javascript: Compare three booleans and return all true booleans 在for循环中触发onchange事件仅运行一次 - Triggering onchange event in a for-loop only runs one time 基本的 For 循环 Javascript 不触发 - Basic For Loop Javascript Not Triggering 用JavaScript触发php循环? - Triggering a php loop with javascript? 为什么当变量为true时JavaScript最终执行DOM语句? - Why is JavaScript executing DOM statements last when a variable is true?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM