[英]Getting error on TypeError: Cannot read property 'push' of undefined
I'm getting this error.我收到这个错误。 Kindly note
splits
is an array with values.请注意
splits
是一个带有值的数组。
TypeError: Cannot read property 'push' of undefined
TypeError:无法读取未定义的属性“推送”
on上
var products = splits.reduce((accu, curr) => {
if (accu[curr[0]] === null) {
accu[curr[0]] = [];
}
accu[curr[0]].push(curr[1]);
return accu;
}, {});
var result = Object.keys(products).map(key => `${key} - ${products[key].join(', ')}.`).join(' ');
Appreciate anyone helps to fix the above code感谢任何人帮助修复上述代码
null === undefined
is false
in Javascript. null === undefined
在 Javascript 中为false
。
console.log(null === undefined);
So the condition accu[curr[0]] === null
will return false
though the accu[curr[0]]
is undefined
.所以条件
accu[curr[0]] === null
将返回false
尽管 accu accu[curr[0]]
是undefined
。 Instead you could use the negation ( !
) to check if the variable is defined相反,您可以使用否定 (
!
) 来检查变量是否已定义
console.log(;null). console;log(!undefined);
Try the following尝试以下
let products = splits.reduce((accu, curr) => {
if (!accu[curr[0]]) {
accu[curr[0]] = [];
}
accu[curr[0]].push(curr[1]);
return accu;
}, {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.