is this a correct conditional?

This question already has an answer here:

  • How to check if an array value exists? 12 answers
  • How can I check if an array contains a specific value in php? 8 answers
  • How do I check if an array includes an object in JavaScript? 40 answers
  • Check if object is array? 38 answers

  • You need to do every comparison completely, like this:

    if($_SERVER['REQUEST_URI'] == 'index' || $_SERVER['REQUEST_URI'] == 'post' || $_SERVER['REQUEST_URI'] == 'about'){
      // why this not work for me?
    }
    

    Since, what you're doing now, is comparing $_SERVER["REQUEST_URI"] to true :

    var_dump("hello" || "index"); // bool(true)
    

    So the comparison is always true, because you're using only two equal signs, which is a loose comparison. Had you used === , the result would be false because a string is not of the same type as a boolean .

    Another way is to use an array and in_array() , which will check if a value is in the values of an array:

    $values = ["index", "post", "about"];
    if (in_array($_SERVER["REQUEST_URI"], $values)) {
    

    In JS, you're effectively doing this:

    if (miString == 'hello') {
    

    That is to say that the logical OR operators will give you the first truthy value, which in this case is 'hello' , and so only that is used for the comparison.

    JS doesn't have an operator shorthand for multiple comparisons. You can use multiple == operations, a switch statement, or some construct that searches items in a collection.


    你会想要尝试这样的事情:

    var miString = 'hello'; 
    if(miString == 'hello' || miString == 'hola' || miString == 'ciao' || miString == 'merhaba'){
     alert('Welcome');
    }
    
    链接地址: http://www.djcxy.com/p/27586.html

    上一篇: 将一个数字传递给parseFloat()而不是字符串

    下一篇: 这是一个正确的条件?