[英]Purpose of logical operators on strings in Javascript
我偶然发现了一些我希望有人可以向我解释的代码。
这在jqGrid的上下文中使用。
onSelectRow: function(id){
if(id && id!==lastsel){
jQuery('#rowed3').jqGrid('restoreRow',lastsel);
jQuery('#rowed3').jqGrid('editRow',id,true);
lastsel=id;
}
},
如上所示,为什么要对javascript中的字符串使用逻辑运算符? 这仅仅是一个错误还是这里我不了解某些功能?
代码取自http://trirand.com/blog/jqgrid/rowedex3.html
完整示例http://trirand.com/blog/jqgrid/jqgrid.html >行编辑>使用事件
变量应为numeri,但条件将以两种方式起作用。
if(id && id !== lastsel)
第一个id
表示必须具有一个值。 价值也必须是真实的。 的值是truthy
如果不falsy
,这意味着它只是不能下列之一(从借用11heavens.com ):
false
null
undefined
''
0
NaN
( NaN
是数字类型)
注意:您将在JavaScript其他地方看到与true
相同的比较,特别是for / while循环:
/*1*/ while(id){...} // while id is true, do something /*2*/ for(;id;){...} // same thing, without the incrementation or variable definition
第二部分是说id不能等于lastsel ,这是使用的最后一个id。 !==
在JavaScript中是特殊的,意味着它必须比较值和类型,而!=
仅比较值:
a == b
:的值a
等于值b
a != b
价值a
不的不相等值b
a === b
:的值a
等于值b
和类型的a
等于类型b
a !== b
价值a
不的不相等值b
和类型的a
不等于类型b
另外,如果您在括号中看到该表达式,则可能有助于考虑该表达式:
if( (id) && (id !== lastsel) )
好吧,为什么不呢?
(id) && (id !== lastsel) // parentheses added for logical emphasis
这表示if (id is trueish) and (not equal to lastsel)
。 “Trueish”是指它不是false
, undefined
或其他任何falsy
。 if (id)
等同于if (id == true)
。 id
不必是字符串(正如注释所指出的那样,它可能永远不会是),并且此检查可确保它不是不应有的东西。 它正在检查变量 ,而不是字符串。
因此,这就是说id必须被定义并且不等于lastsel。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.