Pergunta

I'm trying to use the code below and it works the way I want it by alerting with honda, toyota, and ford in the second each(). But the first one just outputs 0. Why is it doing that?

var cars = {
        honda : {0: "Accord", 1: "Prelude", 2: "Civic"},
        toyota: {0: "Camry", 1: "Corolla", 2: "BRZ"},
        ford: {0: "Mustang", 1: "Focus"}
}

$(cars).each(function(key, value)) {
    alert(key);
})

$.each(cars, function(key, value) {
    alert(key);
})
Foi útil?

Solução

Your first example outputs 0 because when you do $(cars), you're wrapping your cars object in a jQuery object, an object with one element with index 0.

Also you should note the distinction between both "each" methods:

jQuery.each() or $.each():

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.

.each():

Iterate over a jQuery object, executing a function for each matched element.

Outras dicas

try this, to loop through an array:

for (i=0; i<cars.length; i++){
    alert (cars[i]);
} 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top