Jquery OR || operator not working

前端 未结 3 852
余生分开走
余生分开走 2021-01-29 11:54

it\'s a really simple question. The or operator is not working, i am trying to display a different function for both the title and amount field name. Thank you

$         


        
相关标签:
3条回答
  • 2021-01-29 12:11

    You either have to restate the condition like

    if (field.name === "title" || field.name === "amount")
    

    or you can use an array

    if (["title","amount"].indexOf(field.name) > -1)
    
    0 讨论(0)
  • 2021-01-29 12:11

    Your code is executing like this:

    temp = "title" || "amount"; // two "true" values, so "title" is assigned
    if (field.name == temp);{ ... };
    

    which is effectively:

    temp = "title";
    if (field.name == temp) { ... }
    

    To test one varaible against multiple strings, you have to write out the individual tests directly:

    if ((field.name == "title") || (field.name == "amount")) { ... }
    

    and if you need to test against MANY items for which this kind of stuff would get tedious, you can try an array:

    if (["title", "amount", ...].indexOf(field.name) > -1) { ... }
    
    0 讨论(0)
  • 2021-01-29 12:14

    You can't use || like that.

    You need to do:

    if (field.name === "title" || field.name === "amount")
    

    Each statement on either side of the OR are completely separate, and evaluate themselves to be a single boolean value, true or false. Therefore, field.name === "title" will evaluate itself to be true or false, and then "amount" will try to evaluate itself as true or false.

    I believe anything non-empty and non-zero is treated as true, so your OR statement will always be true as "amount" will always evaluate to true.

    You can also do:

    if (["title", "amount"].indexOf(field.name) > -1)
    

    This is especially useful if you have more than 2 values to test.

    0 讨论(0)
提交回复
热议问题