Javascript中字符串上逻辑运算符的用途

Max*_*ich 0 javascript string operators jqgrid

我偶然发现了一些我希望有人可以向我解释的代码.

这在jqGrid的上下文中使用.

onSelectRow: function(id){ 
     if(id && id!==lastsel){ 
          jQuery('#rowed3').jqGrid('restoreRow',lastsel);
          jQuery('#rowed3').jqGrid('editRow',id,true); 
          lastsel=id; 
     } 
}, 
Run Code Online (Sandbox Code Playgroud)

为什么在javascript中对字符串使用逻辑运算符,如上所示?这只是一个错误还是这里有一些我不明白的功能?

代码来自http://trirand.com/blog/jqgrid/rowedex3.html

完整示例http://trirand.com/blog/jqgrid/jqgrid.html >行编辑>使用事件

vol*_*ron 6

变量应该是数字,但是条件可以以任何方式工作.


if(id && id !== lastsel)


  1. 首先id是说它必须具有价值. 价值也必须是真实的.truthy如果不是值falsy,则表示它不能是以下之一(从11heavens.com借来):

    • false
    • null
    • undefined
    • 空字符串 ''
    • 数字 0
    • 号码NaN(NaN型号)


    注意:您将看到与trueJavaScript中其他地方相同的比较,特别是/ while循环:

    /*1*/ while(id){...} // while id is true, do something
    /*2*/ for(;id;){...} // same thing, without the incrementation or variable definition
    
    Run Code Online (Sandbox Code Playgroud)



  2. 第二部分是说id不能等于lastsel,这是最后使用的id.!==JavaScript中的特殊功能意味着它必须比较值和类型,而!=只是比较值:

    • a == b:a等于的值b
    • a != b:值a不等于b
    • a === b:aequals值的值baequals类型的类型b
    • a !== b:值a不等于值b和类型a不等于类型b


编辑


另外,如果您在括号中看到它,可能有助于思考表达式:
if( (id) && (id !== lastsel) )

  • 对你答案的"编辑"部分的小评论:`!==`的优先级高于`&&`(参见例如https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence)和` &&`从左到右工作.因此不需要支架. (2认同)