[英]Get rid of `undefined` in a array of objects
I have this function that receives params as an argument: 我有此函数接收参数作为参数:
export const addCalculations = (params) => {
console.log(params);
};
Then I want to access to the id
value but when I do params[0].id
it throws an error (Cannot read property id of undefined). 然后,我想访问id
值,但是当我执行params[0].id
它将引发错误(无法读取未定义的属性id)。 When I see the console, that function is being called multiple times and it returns undefined
sometimes. 当我看到控制台时,该函数被多次调用,有时返回undefined
。 How can I get rid of those undefined and only get the last array? 如何摆脱那些未定义的对象,而只获取最后一个数组?
params[0]
itself is undefined
so before going to call params[0].id
you should make a check params[0]
本身是undefined
因此在调用params[0].id
,应进行检查
if (params[0]) {
id = params[0].id;
...
}
If you want to filter the array of params, you can use filter
function 如果要过滤参数数组,可以使用filter
功能
filterd = params.filter( x => {
if (x) {
return true;
}
return false;
})
//continue with filtered
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.