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

后端 未结 3 2002
春和景丽
春和景丽 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条回答
  •  南笙
    南笙 (楼主)
    2021-01-23 06:43

    It's the same as:

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

    JavaScript will evaluate the left side (index >= 0), if it's false the && (AND) will short circuit (since false AND anything is false), thus not running `count++.

    If it's (index >= 0) true, it evaluates the right side (count++), then it just ignores the output.

提交回复
热议问题