【问题标题】:Why does this code runs correctly with loose equality than with strict equality?为什么此代码在松散相等而不是严格相等时正确运行?
【发布时间】:2020-07-24 21:39:01
【问题描述】:

我尝试使用严格相等和松散相等对 sn-ps 进行编码,以计算给定数组中 truthy 值的总数。

代码在松散相等的情况下正确运行

let array = [0, '0', true, 100, false, NaN];

countTruthy(array);

function countTruthy(array){
    let count = 0 ;
    
    for (let element of array){
        if (element == (null || undefined || NaN || false || 0 || '')){ //comparing with loose equality
            continue;
        }
        console.log(element);
        count++
    }
    console.log (`The total truthy in the array is : ${count}`);
}

虽然代码给出了严格相等的错误计数。

let array = [0, '0', true, 100, false, NaN];

countTruthy(array);

function countTruthy(array){
    let count = 0 ;
    
    for (let element of array){
        if (element === (null || undefined || NaN || false || 0 || '')){//Using the strict equality
            continue;
        }
        console.log(element);
        count++
    }
    console.log (`The total truthy in the array is : ${count}`);
}

我也试过了

console.log(undefined === undefined);

为什么我在严格相等时得到错误的计数,而在松散相等时得到正确计数?

我也知道编写相同代码的有效方法。因此,请仅针对我面临的上述问题提出建议。

【问题讨论】:

    标签: javascript arrays for-of-loop


    【解决方案1】:

    当您使用||s 链时,整个表达式将评估为第一个真值(如果有) - 否则,它将评估为最终(假)值。所以

    (null || undefined || NaN || false || 0 || '')
    

    等价于

    ('')
    

    在严格相等的情况下,数组项都不是空字符串,所以都通过了测试。

    在松散相等的情况下,空字符串只有 0 和 false 是 ==。

    console.log(
      0 == '',
      false == ''
    );

    与Abstract Equality Comparison:

    对于0 == '':当一个数字与右边的字符串进行比较时,字符串被转换为数字,0 == 0 为真

    1. 如果 Type(x) 是 Number 并且 Type(y) 是 String,则返回比较结果 x == ToNumber(y)。

    对于false == '':当布尔值与右边的字符串进行比较时,布尔值首先转换为数字:

    1. 如果 Type(x) 是 Boolean,则返回比较结果 ToNumber(x) == y。

    然后将字符串转换为数字:

    1. 如果 Type(x) 是 Number 并且 Type(y) 是 String,则返回比较结果 x == ToNumber(y)。

    而0 == 0 是真的。

    【讨论】:

      【解决方案2】:

      我想补充一点,您的代码实际上并没有正确计算真实值 - 您的数组中有 3 个真实值(“0”、true、100)。 问题来自将 NaN 等同于松散和严格相等。与任何事物相比,NaN 总是错误的,甚至:

      NaN === NaN; //false
      NaN == NaN; //false
      

      这就是为什么您的代码使用松散相等计算 4 个值而不是 3 个值的原因。 检查值是否真实的更好方法是让 Javascript 将其转换为布尔值:

      function countTruthy(array){
      let count = 0 ;
      
      for (let element of array){
          if (!element)
              {
              continue;
              }
          count++;
          }
      return  count; 
      

      }

      【讨论】:

        猜你喜欢
        • 2011-06-25
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 2023-01-19
        相关资源
        最近更新 更多