Foreach循环javascript失败

amo*_*mof 1 javascript jquery

为什么每个语句都会导致我的代码中断?我还要用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++;
});
Run Code Online (Sandbox Code Playgroud)

Cla*_*diu 8

首先,email应该是对象文字,而不是数组文字:

var email = {};
Run Code Online (Sandbox Code Playgroud)

其次,email['e_attachments']在尝试使用它之前没有定义.这可能是阻止它工作的原因.尝试添加

email['e_attachments'] = [];
Run Code Online (Sandbox Code Playgroud)

之前$.each.


你可以$.map在这种情况下使用,顺便说一句.那是:

email['e_attachments'] = $.map($('.rowChecked'), function (el) { 
    return $(el).attr('id'); 
});
Run Code Online (Sandbox Code Playgroud)

而不是你的$.each.或者更好的是:

email['e_attachments'] = $('.rowChecked').map(function () { 
    return $(this).attr('id'); 
}
Run Code Online (Sandbox Code Playgroud)