如何统计JavaScript数组对象中指定属性的null值总数量
解决方案
错误原因
- 你尝试访问
theValues.length时,theValues本身是null,基础类型null不存在length属性,因此会返回undefined _.sum是Lodash提供的用于计算数组元素总和的方法,你传入单个null值自然无法得到预期的计数结果
实现代码
适配原有for循环的写法
// 初始化计数变量 let nullCount = 0 for (var i = 0; i < test.length; i++) { // 严格匹配null值,匹配成功则计数+1 if (test[i]['theKey'] === null) { nullCount++ } } console.log(nullCount) // 输出结果为7
更简洁的原生JS写法
1. 用filter过滤后取长度
const nullCount = test.filter(item => item.theKey === null).length
2. 用reduce累计计数
const nullCount = test.reduce((prev, curr) => curr.theKey === null ? prev + 1 : prev, 0)
注意事项
判断null必须使用严格相等运算符===,如果使用宽松相等==,undefined == null的判断结果为true,会把属性值为undefined的项也统计进去,导致结果不符合预期。
内容的提问来源于stack exchange,提问作者doppis
相关产品推荐
相关产品推荐

