Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to refer to anonymous array in a for loop?

for (var name in ['dog','cat','cow']) {
  alert(name);
}

The name here is returning the index of the array, but I can't refer to it since it's anonymous.

I know I can declare it outside the loop, but here I'm asking if is there a way for refering to the name directly that is without index.

like image 905
rsk82 Avatar asked Jan 01 '12 18:01

rsk82


2 Answers

...no. There isn't, not a native loop at least. There is, however, ES5's forEach:

['dog', 'cat', 'cow'].forEach(function(value, key) {
  // do stuff
});

Which is practically the same. It's supported mostly everywhere, except in old IE: something like es5-shim for example enables ES5 methods even in such old browsers, though.

like image 111
goto-bus-stop Avatar answered Sep 30 '22 19:09

goto-bus-stop


You have several options.

If you are using jQuery you can do this:

$.each(['dog','cat','cow'], function() {
    var name = this;
    alert(this);
});

If you are not using jQuery you can create your own function

function each(array, pFunction) {
    for(var i = 0; i < array.length; i++) {
        var element = array[i];
        pFunction(element);
    }
}

each(['dog','cat','cow'], function(name) {
    alert(name);
});

If you don't want to create a function you can always do something crazy like this: (don't recommend it)

for (var name in { 'dog' : '','cat' : null,'cow' : null }) {
    alert(name);
}
like image 22
Luis Perez Avatar answered Sep 30 '22 21:09

Luis Perez