What does shorthand “index >= 0 && count++” do?

后端 未结 3 1996
春和景丽
春和景丽 2021-01-23 06:13

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          


        
3条回答
  •  -上瘾入骨i
    2021-01-23 06:30

    It's equivalent to:

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

    && 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.

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

提交回复
热议问题