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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11778225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:03:16  来源:igfitidea点击:

How do I store data in array within a loop jQuery

javascriptjquery

提问by BentCoder

How do I store data in array within a loop?

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

    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>

回答by Adil

Try this,

尝试这个,

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

other Way for getting id using javascript object instead of jquery for increasing performance.

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

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

EditYou can also use jQuery map()

编辑您还可以使用 jQuery map()

Live Demo

现场演示

arr = $('#cover div').map(function(){
    return this.id;
});

回答by Jaro

javascript Arrays have a method push(el) like this:

javascript 数组有一个像这样的 push(el) 方法:

var images;
var i = 0;

$('#cover div').each(function()
{
    alert($(this).attr('id'));
    images.push($(this).attr('id'));
});

<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>