9

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>

2 Answers 2

29

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.

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

Edit You can also use jQuery map()

Live Demo

arr = $('#cover div').map(function(){
    return this.id;
});
Sign up to request clarification or add additional context in comments.

7 Comments

Why not just push it onto the array instead of wasting time with a counter? Or else use the index argument to the .each callback function.
Any reason for not just using arr.push($(this).attr('id'))?? ... 4 seconds late, haha.
@Benno: Push is slower than the code-sample not using jQuery, see performance test I created: jsperf.com/array-push-vs-insert However, it seems push is faster than the first code-sample using jQuery to select the id. Eitherway, stick to second code-sample in that case.
Thanks for telling @ François Wahl, infact javascript gives performance over jquery usually but it is not with this case .
The reason the first one is fastest is because you aren't running an $.attr call though. jsperf.com/array-push-vs-insert/2.
|
2

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

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.