0

我尝试使用严格相等和松散相等对片段进行编码,以计算给定数组中真实值的总数。

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

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

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

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

4

2 回答 2

2

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

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

相当于

('')

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

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

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

使用抽象相等比较

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

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

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

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

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

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

并且0 == 0是真的。

于 2020-04-12T09:10:08.687 回答
1

我想补充一点,您的代码实际上并没有正确计算真实值 - 您的数组中有 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; 

}

于 2020-04-12T09:39:20.493 回答