user793468
user793468

Reputation: 4976

displaying array elements

I am creating a JavaScript array is the following manner:

var selectedColors= { 'Orange' : $("#Orange").val(),
                         'Light Blue' : $("#LightBlue").val(),
                         'Dark Red' : $("#DarkRed").val(),
                         'Dark Blue' : $("#DarkBlue").val()};

Then loop through each item to see which color was not selected, and then store them in another array:

var colorsNotSelected = [];
$.each(selectedColors, function (key, value) {
    if (value.length == 0)
        colorsNotSelected.push({key:key});
});

Here I want to display the colors not selected, but doing it the following way display the keys: 0,1,2,3 instead of Orange, Light Blue, Dark Red, Dark Blue.

What am I doing wrong here?

if (colorsNotSelected.length > 0)
    $.each(colorsNotSelected, function (key) { alert(key) });
    return false;

Any help is much appreciated.

Upvotes: 0

Views: 77

Answers (2)

SeanCannon
SeanCannon

Reputation: 78046

The object and array would iterate the same in jQuery. It appears you need to use braces to keep that return false statement under check:

if (colorsNotSelected.length > 0) {
    $.each(colorsNotSelected, function (key) { alert(key) });
    return false;
}

This is unnecessary:

colorsNotSelected.push({key:key});

Just do this:

colorsNotSelected.push(key);

This is also assuming somewhere above your example code you have this:

var colorsNotSelected = [];

Upvotes: 1

ContextSwitch
ContextSwitch

Reputation: 2837

You might want to try a for / in loop instead:

for(var i in colorsNotSelected){
   alert(i);
}

Upvotes: 0

Related Questions