为什么这个 each 语句会导致我的代码中断?我还必须使用 javascript 设置索引吗?
var email = [];
email['update'] = true;
email['e_case_id'] = $("#e_case").val();
var i = 0;
$.each($('.rowChecked'), function() {
email['e_attachments'][i] = $(this).attr('id');
i++;
});
最佳答案
首先,email
应该是对象字面量,而不是数组字面量:
var email = {};
其次,您在尝试使用 email['e_attachments']
之前没有定义它。这可能是阻止它工作的原因。尝试添加
email['e_attachments'] = [];
在 $.each
之前。
您可以使用 $.map
在这种情况下,顺便说一句。即:
email['e_attachments'] = $.map($('.rowChecked'), function (el) {
return $(el).attr('id');
});
而不是你的$.each
。或者更好:
email['e_attachments'] = $('.rowChecked').map(function () {
return $(this).attr('id');
}
关于javascript - Foreach 循环 javascript 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16552205/