简体   繁体   English

Javascript:将数组值与变量进行比较

[英]Javascript : Comparing Arrays values to a variable

In my program I have to compare array values to a variable, but it looks like my array is only comparing the last value to the variable. 在我的程序中,我必须将数组值与变量进行比较,但是看起来我的数组只是将最后一个值与变量进行比较。 How should I proceed to compare all of them? 我应该如何比较所有这些?

Here is the code: 这是代码:

for(var n=0; n<arrayLength; n++) {
    console.log(occupiedArray[n][0]);
    if(occupiedArray[n][0] == clickedX  && occupiedArray[n][1] == clickedY ) {
        occupied = true;
    } else {
        occupied = false;
    }
}

And here is my array : 这是我的数组:

var occupiedArray = [[4,0],
                     [5,0],
                     [6,0]];

When I use console.log it displays 4,5,6 just like I wanted, but it's only comparing the '6' value to my variable 'clickedX'. 当我使用console.log时,它就像我想要的那样显示4,5,6,但是它只是将“ 6”值与变量“ clickedX”进行比较。 Any idea? 任何想法?

Thanks 谢谢

You're overwriting the value of occupied each iteration so only the most recent comparison is reflected at the end of the loop. 您将覆盖每次迭代所占用的值,以便在循环结束时仅反映最新的比较。 Instead, try this: 相反,请尝试以下操作:

for(var n=0; n<arrayLength; n++) {
    console.log(occupiedArray[n][0]);
    if(occupiedArray[n][0] == clickedX  && occupiedArray[n][1] == clickedY ) {
        occupied = true;
    }
}

Here occupied can be set to true but once true can never return to false. 可以在这里将占用状态设置为true,但是一旦为true,就永远不会返回false。

maybe.. 也许..

occupied = false;
for(var n=0; n<arrayLength; n++) {
    if((occupiedArray[n][0] == clickedX)  && (occupiedArray[n][1] == clickedY) ) {
        occupied = true;
        break;
    }
}

if occupied found, exit loop 如果发现已占用,则退出循环

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

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