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

后端 未结 3 1998
春和景丽
春和景丽 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:27

    index >= 0 && count++;
    

    First part: index >= 0

    returns true if index has a value that is greater than or equal to 0.

    Second part: a && b

    most C-style languages shortcut the boolean || and && operators.

    For an || operation, you only need to know that the first operand is true and the entire operation will return true.

    For an && operation, you only need to know that the first operand is false and the entire operation will return false.

    Third Part: count++

    count++ is equivalent to count += 1 is equivalent to count = count + 1

    All together now

    If the first operand (index >= 0) of the line evaluates as true, the second operand (count++) will evaluate, so it's equivalent to:

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

    JavaScript nuances

    JavaScript is different from other C-style languages in that it has the concept of truthy and falsey values. If a value evaluates to false, 0, NaN, "", null, or undefined, it is falsey; all other values are truthy.

    || and && operators in JavaScript don't return boolean values, they return the last executed operand.

    2 || 1 will return 2 because the first operand returned a truthy value, true or anything else will always return true, so no more of the operation needs to execute. Alternatively, null && 100 will return null because the first operand returned a falsey value.

提交回复
热议问题