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.
...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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With