gpt4 book ai didi

javascript - 对象数组 : Cannot read property 'id' of undefined inside onchange event

转载 作者:行者123 更新时间:2023-11-30 07:51:57 24 4
gpt4 key购买 nike

如果 id 变量等于对象的 id,我一直在寻找一种从对象数组中删除单个对象的方法。

我使用数组来了解选中了哪些复选框,以便收集相关信息以供进一步处理。

示例:https://jsbin.com/vicerewevi/edit?html,js,output

快速选中复选框时出现的错误:

Uncaught TypeError: Cannot read property 'id' of undefined
at vicerewevi.js:33
at Function.each (jquery-3.1.0.js:368)
at HTMLInputElement.<anonymous> (vicerewevi.js:32)
at HTMLInputElement.dispatch (jquery-3.1.0.js:5110)
at HTMLInputElement.elemData.handle (jquery-3.1.0.js:4918)

如果 value.id == id 行出现以上错误:

// if checkbox is checked, add object to array and if unchecked remove object by 'id' from array
$('.checkbox').change( function(){

var id = parseInt($(this).attr('data-id'))
var foo = $(this).parent().siblings().find('#foo').val()
var bar = $(this).parent().siblings().find('#bar').val()

if($(this).prop('checked')) {
var obj = {'id': id, 'foo': foo, 'bar': bar}
jsonobjects.push(obj)
} else {
$.each(jsonobjects, function( index, value ) {
if (value.id == id ) {
jsonobjects.delete(index)
}
});
}
countChecked() // update count of checkboxes
console.log(JSON.stringify(jsonobjects))
$('#output').html(JSON.stringify(jsonobjects, null, ""))
});

我在下面的 SO 上找到了这段代码(之前从未使用过自定义原型(prototype)):

Array.prototype.delete = function(pos){
this[pos] = undefined;
var len = this.length - 1;
for(var a = pos;a < this.length - 1;a++){
this[a] = this[a+1];
}
this.pop();
}

最佳答案

因为你从你的数组中删除条目,下次你迭代它时,你会得到一个 valueundefined阵列中的特定“间隙”。显然,它没有 id 属性。

要解决这个问题,不要使用delete,而是使用filter 来创建一个新的过滤后的数组,这样就不会有这样的间隙。

替换:

    $.each(jsonobjects, function( index, value ) {
if (value.id == id ) {
jsonobjects.delete(index)
}
});

...与:

    jsonobjects = jsonobjects.filter(function( value ) {
return value.id !== id;
});

或者,如果您想坚持使用 jQuery 方法,请使用 $.grep:

    jsonobjects = $.grep(jsonobjects, function( value ) {
return value.id !== id;
});

关于javascript - 对象数组 : Cannot read property 'id' of undefined inside onchange event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51122173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com