如何从对象内部的数组中删除特定对象? (使用pop()或其他解决方案) [英] How is the specific object removed from the array inside the object? (with pop() or another solution)
问题描述
我想从myObj的年份中删除"hello5".
I want to remove the 'hello5' from the years in myObj.
我使用了"pop"原型,但浏览器控制台返回了此结果:
I used 'pop' prototype, but the browser console return this result :
'未捕获的TypeError:无法读取未定义的属性'type''
以下是我的问题的示例.您可以尝试从控制台查看错误消息.
The following is an example for my issue. You could try and will see error message from console.
我尝试了很长时间,但没有找到任何解决方案,我需要您的建议和解决方案.
I tried a long time but I didn't find any solution, I need your advise and solution.
代码:
var myObj = {
test : 'testObje',
langs : {
0 : 'EN',
1 : 'GR',
2 : 'RU',
3 : 'TR'
},
comment : 'testComment'
};
var years = [];
for (i= 0; i<=10; i++)
{
years.push({
operator : i,
type : 'hello' + i
});
};
myObj.years = years;
var myObjLeng = myObj.years.length;
for(var i = 0; i < myObjLeng; i++) {
if(myObj.years[i].type == 'hello5') {
myObj.years.pop();
}
}
推荐答案
这里有一些不错的选择,所以让我me一下为什么会出现该错误.
There are some good alternatives here, so let me just take a stab at why you're getting that error.
由于更改数组中循环的长度,导致出现此错误.在循环的开始,您有11个元素,并使用该元素定义for
循环将运行多少次.到达hello5
时,关闭pop
最后一个元素,使数组长10个元素.但是,您的for
循环仍将尝试访问第11个元素.这将是undefined
,并且当您尝试访问undefined
的属性(例如type
)时,会出现TypeError.
You're getting that error because you're changing the length of the array mid-loop. At the beginning of the loop, you have 11 elements, and you use that to define how many times your for
loop will go. When you get to hello5
, you pop
the last element off, making your array 10 elements long. However, your for
loop will still try to access the 11th element. That will be undefined
, and when you try to access a proprty of undefined
(e.g. type
), you will get a TypeError.
这篇关于如何从对象内部的数组中删除特定对象? (使用pop()或其他解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!