Javascript 引用递增变量i时for循环出错
我试图检查数组中是否存在对象。基本上,我想做的是,如果一个对象存在,那么将其从数组中移除,或者将该对象推入数组中。但我总是犯错误 从api返回的对象类型:Javascript 引用递增变量i时for循环出错,javascript,arrays,vuejs2,vuex,Javascript,Arrays,Vuejs2,Vuex,我试图检查数组中是否存在对象。基本上,我想做的是,如果一个对象存在,那么将其从数组中移除,或者将该对象推入数组中。但我总是犯错误 从api返回的对象类型: { "id": 23, "status": "Available", "column_id": 5, "row_id": 1 }, { "id": 24, "status": "Available", "column_id": 6, "row_id": 1 }, 我正在使用Vu
{
"id": 23,
"status": "Available",
"column_id": 5,
"row_id": 1
},
{
"id": 24,
"status": "Available",
"column_id": 6,
"row_id": 1
},
我正在使用Vue.js,每当单击某个对象时,我都会在Vuex存储操作中检查该对象是否存在于数组中。但我总是会出错:
未捕获的TypeError:无法读取未定义的属性“id”
store.js:
state: {
selectedSeats: [],
},
actions: {
getSelectedSeats(context, payload) {
let found = false;
if (context.state.selectedSeats.length < 1) {
console.log('empty');
context.commit('mutateSelectedSeat', payload);
}
else {
console.log('not empty');
for (let i = 0; i <= context.state.selectedSeats.length; i++) {
if (payload.id === context.state.selectedSeats[i].id) {
found = true;
break;
}
}
console.log('after loop');
if (found) {
console.log('found');
}
else {
console.log('not found');
}
}
}
}
我认为问题在于变量
I
。但是我不知道我在这里遗漏了什么?如果你console.log(context.state.selectedSeats[I],I)
在if(payload.id==context.state.selectedSeats[I].id)
@AmreshVenugopal Ok,。。我得到了这个未定义的1
。我做错了什么?它应该是I
而不是I,所以确实是undefined
您试图访问id
?你是如何移除物品的?@Xufox是的!天啊。。我从早上就开始调试这个小错误!非常感谢。
...
if (payload.id === context.state.selectedSeats[0].id) {
found = true;
...