简体   繁体   English

“或”条件不起作用JavaScript

[英]“or” condition doesn't work JavaScript

I have a condition which should predict run the function. 我有一个条件可以预测运行该功能。 but it wouldn't work. 但这是行不通的。

if ((event.keyCode !== 40) || (event.keyCode !== 38)) {
        self.inputVal = input.value;
        var result = pokemonNames.filter(function(pokemon) {
          return pokemon.includes(self.inputVal.toLowerCase());
        });
        if (result.length > 5) {
          result = result.filter(function(pokemon, index) {
            return index < 5;
          });
        }

when I use just event.keyCode !== 40 it works fine, but when I use (event.keyCode !== 40) || (event.keyCode !== 38) 当我只使用event.keyCode !== 40它工作正常,但是当我使用(event.keyCode !== 40) || (event.keyCode !== 38) (event.keyCode !== 40) || (event.keyCode !== 38) it would work. (event.keyCode !== 40) || (event.keyCode !== 38) ,它将起作用。

If you want to execute the if block if the event.keyCode is NOT 40 or 38 you want this 如果要在event.keyCode不是40或38的情况下执行if块,则需要这样做

((event.keyCode !== 40) && (event.keyCode !== 38))

If you want to execute the code if event.keyCode is 40 or 38 如果event.keyCode为40或38,则要执行代码

((event.keyCode == 40) || (event.keyCode == 38))

As Aaron pointed out in the comments, it will always resolve as true . 正如亚伦(Aaron)在评论中指出的那样,它将始终被解析为true If the number is 40, the second condition will be true (since it's not 38), and vice versa. 如果数字为40,则第二个条件为true(因为它不是38),反之亦然。 Use && instead and it will work. 使用&&代替,它将起作用。

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

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