0

I trying declare an array, push colection of arrays and iterate colection

My JS:

var colection = [];
var array = ["a1", "a2"];
colection.push(array);
array = ["b1", "b2"];
colection.push(array);

$.each(colection, function(array){
    var p = "<p>1:"+array[0] +
        "<br>2:"+array[1]+"</p>";

    $("#test").append(p);
});

my html:

<div id="test">
</div>

I want that result:

1:a1
2:a2

1:b1
2:b2

but return only:

1:undefined
2:undefined

1:undefined
2:undefined

2 Answers 2

4

The first argument of the function in the each syntax is actually the index of the item so change the script to look like:

var colection = [];
var array = ["a1", "a2"];
colection.push(array);
array = ["b1", "b2"];
colection.push(array);

$.each(colection, function(index, array){
    var p = "<p>1:"+array[0] +
        "<br>2:"+array[1]+"</p>";

    $("#test").append(p);
});

JsFiddle: http://jsfiddle.net/9KVnM/

Edit: Ref: api.jquery.com/jquery.each

Thx Kevin

Sign up to request clarification or add additional context in comments.

Comments

0

You canned to use key value pair in iteration like;

$.each(collection, function(i, array){
    var p = "<p>1:"+array[0] +
        "<br>2:"+array[1]+"</p>";

    $("#test").append(p);
});

Here is demo: http://jsfiddle.net/cubuzoa/JJ9UA/2/

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.