我有一个这样的数组:
var arrSession = [ { name: 'Product 01', groupID: '50303', delivery: 'mail'}, { name: 'Product 02', groupID: '50403', delivery: 'bike'} ]
这个循环删除特定对象:
for(var i=0, len=arrSession.length; i<len; i++) {
if (arrSession[i].groupID == getGroupID && arrSession[i].delivery == getDelivery) {
arrSession.splice(i, 1);
}
}
如果我删除最后一个对象,一切正常:
var getGroupID = 50403;
var getDelivery = bike;
但是如果我要删除第一个对象:
var getGroupID = 50303;
var getDelivery = mail;
我得到一个错误:
TypeError: Cannot read property 'groupID' of undefined
为什么会这样,如何解决?
编辑:
如果只有一个对象也没有问题。
var arrSession = [ { name: 'Product 01', groupID: '50303', delivery: 'mail'} ]
最佳答案
简短回答:由于 for循环语法。 初始化
只发生一次
。 拼接
后,您错过了更新len
。
for ([initialExpression]; [condition]; [incrementExpression]) statement
解决方案:正如其他答案中已经提到的,您可以中断
循环(如果您只添加一个项目,这将起作用)。
const arrSessionActual = [{
name: 'Product 01',
groupID: '50303',
delivery: 'mail'
}, {
name: 'Product 02',
groupID: '50403',
delivery: 'bike'
}];
function removeItem(arrSession, getGroupID, getDelivery) {
for (var i = 0,
len = arrSession.length; i < len; i++) {
if (arrSession[i].groupID == getGroupID && arrSession[i].delivery == getDelivery) {
arrSession.splice(i, 1);
len = arrSession.length; // This is missing
}
}
console.log(arrSession);
}
removeItem(arrSessionActual.slice(), 50403, 'bike');
removeItem(arrSessionActual.slice(), 50303, 'mail');
关于javascript - 拼接第一个对象返回TypeError : Cannot read property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62475521/