[英]Javascript: using Logical Operators with Comparison Operators
I am trying to understand how to use logical operators with my code and be as efficient as possible. 我试图了解如何在我的代码中使用逻辑运算符,并使其尽可能高效。
Let's say I have this variable: 假设我有这个变量:
var key = localStorage.getItem('keyName');
And this is my conditional: 这是我的条件:
if (key !== null && key !== '' && key !== ' ') { // localStorage key exists and is not empty or a single space
// Do something with key
}
Is there a way to write it more efficiently? 有没有办法更有效地编写它? I tried this, but it's not working:
我试过了,但是没有用:
if (key !== null && '' && ' ') {
// Do something with key
}
if( value ) {
}
will evaluate to true if value is not: 如果值不是,则将评估为true:
so key !== null && key !== ''
can be replaced by key
所以
key !== null && key !== ''
可以替换为key
We can use /\\S/.test(key)
to test for a string that is just spaces (1 or more) 我们可以使用
/\\S/.test(key)
测试仅是空格(1个或更多)的字符串
so how about 那怎么样
if (key && /\S/.test(key) ){
}
or alternatively 或者
if (key && key.trim()){
}
You may simply use: 您可以简单地使用:
if(key) {
// to do here
}
Taking care of whitespace: 照顾空格:
if(key && key.replace(/\s/g,'')) {
//
}
You can use the trim()
method to remove any leading or trailing whitespace characters from a string. 您可以使用
trim()
方法从字符串中删除任何前导或尾随空格字符。 There is no shorthand notation as you did in your second code example. 没有第二个代码示例中那样的速记符号。
if (key !== null && key.trim() !== '')
// Do something with key
}
if(!~[null, '', ' '].indexOf(key))
or 要么
if(!~[null, ''].indexOf(key.trim()))
Explanation: 说明:
indexOf return int>=0. indexOf返回int> = 0。 Int >=0 means the element is found.
Int> = 0表示找到了元素。 All result will evaluate to true except 0, that's where
~
(invert/negate the result and subtract 1) comes handy. 除0以外,所有结果的计算结果均为true,这是
~
(求反/求反并减去1)的地方。
Rest is self-explanatory, please let me know if any further explanation is required. 休息是不言自明的,如果需要任何进一步的说明,请告诉我。
try: 尝试:
if (key && key.trim())
the first check fails if key is null, and the second check fails if key is only whitespace. 如果key为null,则第一次检查失败,如果key为空白,则第二次检查失败。 If either check fails, the whole thing fails.
如果任何一项检查失败,则整个操作都会失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.