这个简写是什么? [英] What does this shorthand do?

查看:163
本文介绍了这个简写是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我发现这个奇怪的简写时,我正忙着读 underscore.string 函数:

I was killing time reading the underscore.string functions, when I found this weird shorthand:

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;
}

法律声明:没有把功劳归功于 underscore.string

我把这条线放在这里,所以你不会浪费时间去找它:

I put the line alone here, so you don't waste time finding it:

index >= 0 && count++;

我从未见过类似的东西。

I have never seen anything similar to that. I am clueless in what is doing.

推荐答案

相当于:

if (index >= 0) {
    count = count + 1;
}

&& 是逻辑AND运算符。如果 index> = 0 为true,那么也会计算右边的部分,它会将 count 加1。
如果 index> = 0 为false,则不计算右边部分,所以 count 没有改变。

&& is the logical AND operator. If index >= 0 is true, then the right part is also evaluated, which increases count by one.
If index >= 0 is false, the right part is not evaluated, so count is not changed.

此外,&& 稍微更快 而不是 if if 方法,如这个JSPerf

Also, the && is slightly faster than the if method, as seen in this JSPerf.

这篇关于这个简写是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆