我似乎无法通过这个测试:
hasNull([1, null, 3])
预期:true
但得到:false
我的功能:
function hasNull(arr) {
return arr.some((item)=>{ item === null }) ? true : false
}
最佳答案
我让它比你的解决方案短了一点。如果您从数组函数中删除大括号 {}
,那么它将返回 item === null
的值,除此之外,它只是 undefined
这就是为什么它不从数组中为 some()
传递任何值的原因。
另外一个建议是三元运算符在这种情况下是无用的,因为 Array.prototype.some()
已经返回一个 boolean
,请参阅文档:
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
我想这对您来说适用于以下一种衬垫:
const hasNull = arr => arr.some(item => item === null);
console.log(hasNull([1, null, 3]));
希望对您有所帮助!
关于javascript - 使用某种方法编写一个函数来检查数组中的项目是否等于 null (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59584054/