0

Is there a short hand notation for iterating through a javascript array that yields the actual object, instead of the index of the object?

For example:

var dataset = ['a','b','c']

for (item in dataset){
    console.log(item);

}

I want to log 'a','b','c' -- not 0,1,2.

My reason for not wanting to use dataset[item] is that I have several nested for loops, and the code is getting very verbose.

corycorycory
  • 1,448
  • 2
  • 23
  • 42

2 Answers2

1

If you're willing to use jQuery (which can blend well with basic JS), it's as simple as this:

var dataset = ['a', 'b', 'c'];
$(dataset).each(function (i, o) {
    console.log(o);
});

What this does, essentially, is performs a foreach loop on dataset, treating it like an array containing objects. The index is stored in i and a non-jQuery object is stored in o. You can use $(o) to get the jQuery version of this object.

Hope this helps!

0

Turns out this can be accomplished using the forEach loop:

dataset.forEach(function(item){
    console.log(item);
});
corycorycory
  • 1,448
  • 2
  • 23
  • 42