如何在循环jQuery中将数据存储在数组中

Ben*_*der 8 javascript jquery

如何在循环中将数据存储在数组中?

    var images;
    var i = 0;

    $('#cover div').each(function()
    {
        alert($(this).attr('id'));
        //I should store id in an array
    });


    <div id="cover">
        <div id="slider_1"><p class="content">SLIDER ONE</p></div>
        <div id="slider_2"><p class="content">SLIDER TWO</p></div>
        <div id="slider_3"><p class="content">SLIDER THREE</p></div>
    </div>
Run Code Online (Sandbox Code Playgroud)

Adi*_*dil 27

试试这个,

var arr = [];
i = 0;
$('#cover div').each(function()
{
        alert($(this).attr('id'));
        arr[i++] = $(this).attr('id');
        //I should store id in an array
});
Run Code Online (Sandbox Code Playgroud)

其他使用javascript对象而不是jquery来获取id以提高性能的方法.

var arr = [];
i = 0;
$('#cover div').each(function()
{
      arr[i++] = this.id;
});
Run Code Online (Sandbox Code Playgroud)

编辑你也可以使用jQuery map()

现场演示

arr = $('#cover div').map(function(){
    return this.id;
});
Run Code Online (Sandbox Code Playgroud)

  • 为什么不把它"推"到阵列而不是浪费时间与计数器?或者使用`.each`回调函数的index参数. (3认同)