简体   繁体   English

for循环,如果if语句javascript不能按预期工作

[英]for loop in if statement javascript not working as expected

The idea behind this code is pretty simply when some one click on the button, insert the one false value if it does not exist, to do that, i created the for loop, which check how many false value exist, and if they are less than one than insert the false value else do nothing 这段代码的思想很简单,当有人单击按钮时,如果不存在则插入一个错误值,为此,我创建了for循环,该循环检查存在多少错误值,以及是否存在较少的错误值比插入假值多一个,否则什么都不做

here is the the code 这是代码

addNote(index){
    const order = this.state.order
    var j =0;
    const note=order[index].note
    for(var i =0; i<note.length; i++){
        if(note[i].display===false){j++;}
        if(j==0){note[note.length]={display:false}}
        console.log(j)
    }
    console.log(note)
    this.setState({order:this.state.order}) 
}

if you see the console log result, it is increasing the value for j for each click, than why my if statement is working for each click, it should only work if the value for j is zero, i am talking about this line if(j==0){note[note.length]={display:false}} 如果您看到控制台日志结果,它将增加每次单击的j值,而不是为什么我的if语句对每次单击有效,它仅在j的值为零时才有效,我在说的是if(j==0){note[note.length]={display:false}}

here is the array before any click 这是单击之前的数组

0:Object
        display:true
        note:"jhj"

the array after second click 第二次单击后的数组

0:Object
        display:true
        note:"jhj"
    1:Object
        display:false

the array after second click 第二次单击后的数组

 0:Object
    display:true
    note:"jhj"
1:Object
    display:false
2:Object
    display:false

If both if statements are inside the loop, then you will add a new entry to the array every time addNote is called. 如果两个if语句都在循环内,则每次调用addNote 时,都 addNote数组添加一个新条目。 That's because j is always 0 in the first iteration of the loop and because note[0].display is true , it stays 0 . 这是因为j在循环的第一次迭代中始终为0 ,并且因为note[0].displaytrue ,所以它保持为0 Then of course if (j==0) is true , adding a new element to the array. 当然, if (j==0)true ,则向该数组添加一个新元素。 In other words, you are deciding whether or not to add a new entry by looking at each element individually, not together. 换句话说,您正在决定是否通过单独(而不是一起)查看每个元素来添加新条目。

if they are less than one than insert the false value else do nothing 如果它们小于一个,则插入错误值,否则不执行任何操作

That's not what your code is doing. 那不是你的代码在做什么。 Your code inserts a new value if any entry has display: true . 如果任何条目display: true则您的代码将插入一个新值display: true Since the first element has that, your code always adds a new entry. 由于第一个元素具有该元素,因此您的代码总是添加一个新条目。

The following code would do what you want (instead of the loop): 以下代码将完成您想要的事情(而不是循环):

if (!note.some(item => item.display === false)) {
  note.push({display:false});
}

Which translates to "if there is not an element with display === false add a new element. 转换为“如果没有display === false的元素,则添加新元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM