我尝试使用严格相等和松散相等对片段进行编码,以计算给定数组中真实值的总数。
代码在松散相等的情况下正确运行
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);
为什么我在严格相等时得到错误的计数,而在松散相等时得到正确计数?
我也知道有一种有效的方法来编写相同的代码。因此,请仅针对我面临的上述问题提出建议。