【发布时间】:2018-12-09 20:31:30
【问题描述】:
如果 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(以前从未使用过自定义原型)上找到了以下代码:
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();
}
【问题讨论】:
-
你试过用
value.getAttribute("id") == id代替value.id == id吗?如果它是一个元素? -
顺便说一句,不用那种奇怪的
delete方法,你可以直接用jsonobjects.splice(index, 1) -
@JonasW。谢谢,我还在简单的 for 循环中添加了 hasownproperty 而不是 $.each 来检查数组中的元素是否不是数组函数
标签: javascript jquery arrays checkbox