aja*_*221 2 javascript shorthand
当我发现这个奇怪的简写时,我正在浪费时间阅读underscore.string函数:
function count (str, substr) {
var count = 0, index;
for (var i = 0; i < str.length;) {
index = str.indexOf(substr, i);
index >= 0 && count++; //what is this line doing?
i = i + (index >= 0 ? index : 0) + substr.length;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
合法:在使用上述函数之前请三思而后,不要使用underscore.string
我把这条线放在这里,所以你不要浪费时间找到它:
index >= 0 && count++;
Run Code Online (Sandbox Code Playgroud)
我从未见过类似的东西.我无知在做什么.
它相当于:
if (index >= 0) {
count = count + 1;
}
Run Code Online (Sandbox Code Playgroud)
&&是逻辑AND运算符.如果index >= 0为真,那么也会评估正确的部分,它会增加count1.
如果index >= 0为false,则不评估正确的部分,因此count不会更改.
此外,&&是稍微比快if的方法,如在此JSPerf.
index >= 0 && count++;
Run Code Online (Sandbox Code Playgroud)
index >= 0如果index其值大于或等于,则返回true 0。
a && b大多数C风格的语言都会快捷化boolean ||和&&operator。
对于||操作,您只需要知道第一个操作数为true,整个操作将返回true。
对于&&操作,您只需要知道第一个操作数为false,整个操作将返回false。
count++count++等价于count += 1等价于count = count + 1
如果该行的第一个操作数(index >= 0)的计算结果为true,则第二个操作数(count++)的计算结果为,因此等效于:
if (index >= 0) {
count = count + 1;
}
Run Code Online (Sandbox Code Playgroud)
JavaScript与其他C风格语言不同,它具有truthy和falsey值的概念。如果一个值的计算结果为false,0,NaN,"",null,或undefined,它是falsey; 所有其他值均为truthy。
||而&&在JavaScript符不返回布尔值,他们返回最后执行的操作。
2 || 1将会返回,2因为第一个操作数返回了一个truthy值,true否则其他任何东西将始终返回true,因此不再需要执行任何操作。或者,null && 100将返回,null因为第一个操作数返回了一个falsey值。