javascript - 对象数组:无法读取 onchange 事件中未定义的属性“id”
问题描述
如果 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();
}
解决方案
因为您delete
从数组中输入,所以下次迭代它时,您将得到一个value
用于undefined
数组中特定“间隙”的值。显然,它没有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;
});
推荐阅读
- python - Heroku 无法部署 python Pandas 应用程序
- image - 在 RStudio 中生成 PDF、jpeg 或其他图像时遇到问题
- c# - 如何从已发送的电子邮件中检索(google api)
- javascript - Rock Paper Scissor Javascript 只让我绑定,无论我在调用函数时输入什么。我不明白我哪里出错了?
- javascript - 将 IndexedDB 数据迁移到 JS 中的数组
- amazon-web-services - AWS Copilot - 改为部署/创建 https 端点
- c# - C#:有没有办法通过指定额外参数的值来“修剪”一个函数以适应委托?
- laravel - 计算的 vue js 不适用于惯性
- php - 如何安装 Microsoft Azure 存储 PHP 客户端库
- go - GoLand 设置终端单元不起作用