检查谓词(第二个参数)在集合(第一个参数)的所有元素是否为 truthy。
换句话说,你将获得一个对象的数组集合。 如果数组中的每个对象里,pre
对应属性值均为 truthy
,则返回 true
。 否则,返回 false
。
JavaScript 中,如果一个值在 Boolean 的上下文中的执行结果为 true
,那么我们称这个值是 truthy
的。
别忘了,你可以使用点号表示法或方括号表示法([]
)来访问对象的属性。
刚开始有点不理解题意,看两遍测试案例就懂了
测试案例(后四个):
truthCheck([{"single": "yes"}], "single")
应返回true
。
truthCheck([{"single": ""}, {"single": "double"}], "single")
应返回false
。
truthCheck([{"single": "double"}, {"single": undefined}], "single")
应返回false
。
truthCheck([{"single": "double"}, {"single": NaN}], "single")
应返回false
。
注意事项:判断NaN在这里不能使用typeof,它 “不是一个数字”,但是 NaN 的 typeof 结果却是 number,
NaN 和任何变量都不相等,包括 NaN 自己。
在这里使用 isNaN()进行判断。
通过代码
function truthCheck(collection, pre) {
let sum = 0;
for(let i = 0;i < collection.length;i++){
if(collection[i][pre] == undefined
|| collection[i][pre] ==''
|| Number.isNaN(collection[i][pre]) != false)
continue;
sum++;
}
if(sum == collection.length){
return true;
}
return false;
}
truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");