以下是一个简单的代码段:
pass="Hello";
count=pass.match(/[A-Z]/g);
count=(count && count.length || 0);
alert(count); //1
我只是没有了解第三行是如何工作的,count=(count && count.length || 0);
。背后的逻辑是什么?谢谢!
答案 0 :(得分:4)
它的缩写:
if (count) {
count = count.length;
} else {
count = 0;
}
答案 1 :(得分:3)
它基本上等同于
count = (count)? count.length : 0;
或更明确地
if (count)
count = count.length;
else
count = 0;
答案 2 :(得分:1)
如果您希望用英文编写,则表示
如果count
truthy ,请获取count.length
,如果count.length
falsy ,请获取0
。如果count
falsy ,请获取0
。设置count
等于我们得到的。
你可以想到像这样 truthy ( falsy 是反向的)
function isTruthy(x) {
if (x) return true;
return false;
}
答案 3 :(得分:0)
基本上,a=(a && b || c);
是
if (a)
a=b
else
a=c
我同意,因为我测试了一个in {-1,0,null,1}。一开始让我感到困惑的是我认为逻辑运算总会返回true / false或1/0值。但现在我学到了一些新东西。谢谢大家!