Foreach循环javascript失败

时间:2013-05-14 20:24:06

标签: 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++;
});

1 个答案:

答案 0 :(得分:8)

首先,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'); 
}