2 回答

TA贡献1818条经验 获得超7个赞
Array.forEach()
返回值被忽略,并且您不能像在for...in
. Array.some()
一旦检查失败,您就可以使用您的案例返回结果。
注1:Array.some()
将返回true
只要检查返回true
。只有当所有支票Array.every()
都返回时true
才会返回true
。
注意 2:true
如果至少有一个null
或''
值,您的函数背后的想法似乎是返回,但您的代码却恰恰相反。false
当有空项目时,您可以否定我的函数的结果。
注 3:Array.keys/values/entries
withArray.forEach()
和for...in
循环之间还有另一个区别。该for...in
循环还将循环所有继承的可枚举属性,而这些Object.x()
方法只会迭代自己的可枚举属性。
// use object values, I use Object.entries to show the key in the console
const checkHasEmpty = obj => Object.entries(obj).some(([key, value]) => console.log(`key: ${key}`) || value === null || value === '')
console.log(checkHasEmpty({}))
console.log(checkHasEmpty({ a: 1, b: null, c: 3 }))
console.log(checkHasEmpty({ a: '', b: 2 }))
console.log(checkHasEmpty({ a: 1, b: 2, c: null }))

TA贡献1770条经验 获得超3个赞
似乎在第二个片段中,错误就在这里
Object.keys(obj).forEach(key => {
if (obj[key] === null || obj[key] === '') {
forEach将接受参数,因为(item,index)whereitem是数组的元素,是数组index中的当前索引。
因此obj[key]将尝试获取键指定的数组中的元素,该元素也可以是未定义的
试试这个obj[key]只替换key或obj[index]
Object.keys(obj).forEach(key => {
if (key === null || key === '') {
添加回答
举报