Javascript 如何从元素集获取id并保存在数组中?

Javascript 如何从元素集获取id并保存在数组中?,javascript,jquery,arrays,Javascript,Jquery,Arrays,我想保存数组中元素集的id,但只保存最后一个元素的id HTML: 使用map(): 这将获得所有这些,您在循环的每次迭代中都会重新初始化数组。在数组中收集您的id,然后将结果写入div: var ids = []; $('.div').each(function(n){ ids.push($(this).attr('id')); }); $('#test').html(ids.join(',')); 您可以使用.map(): 演示:使用您自己的代码帮助您了解发生了什么:

我想保存数组中元素集的id,但只保存最后一个元素的id

HTML:

使用
map()


这将获得所有这些,您在循环的每次迭代中都会重新初始化数组。

在数组中收集您的id,然后将结果写入div:

var ids = [];

$('.div').each(function(n){
    ids.push($(this).attr('id'));
});

$('#test').html(ids.join(',')); 

您可以使用
.map()


演示:

使用您自己的代码帮助您了解发生了什么:

// create the array outside of the loop - don't recreate it on each iteration of the loop.
var test = new Array();

// loop over the divs and push each ID into the array
$('.div').each(function(n){
    test.push($(this).attr('id'));
});

// display the IDs
$('#test').html(test.join(', ')); 

使用小提琴的示例:

我修复了@Pinal,这是迄今为止最短的答案:)get()做什么?
map
返回一个包装在jQuery对象中的数组
get
返回数组本身。
var ids = $('.div').map(function() {
    return this.id;
}).get();
$('#test').text(ids.join(','));
   var test = new Array();
    $('.div').each(function(n){
        test.push($(this).attr('id'));
        $('#test').html(test); 
    });
var ids = [];

$('.div').each(function(n){
    ids.push($(this).attr('id'));
});

$('#test').html(ids.join(',')); 
$('#test').html($('.div').map(function(){
    return $(this).attr('id');
}).get().join());
// create the array outside of the loop - don't recreate it on each iteration of the loop.
var test = new Array();

// loop over the divs and push each ID into the array
$('.div').each(function(n){
    test.push($(this).attr('id'));
});

// display the IDs
$('#test').html(test.join(', '));