Is it possible to reference an anonymous array in a for loop?

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

name here returns the index of the array, but I cannot reference it, since it is anonymous.

I know that I can declare it outside the loop, but here I ask if there is a way to refer to a name directly that does not have an index.

+7
source share
7 answers

If you know that the keys of the array will be integer, then nothing requires using the for..in construct.

 for (var arr = ['dog','cat','cow'], name = 0; name < arr.length; name++ ) { console.log(arr[ name ]); } 

In the above code, a simpler for loop allows you to create a new object and reference the key inside the loop.

+5
source

... not. At least not, not your own cycle. However, there is ES5 forEach :

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

This is practically the same. It supported mostly everywhere , except for the old IE: something like es5-shim , for example, includes ES5 methods even in such old browsers.

+13
source

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: (not recommended)

 for (var name in { 'dog' : '','cat' : null,'cow' : null }) { alert(name); } 
+4
source

If the array is anonymous, you cannot reference its elements using the for in loop.

+3
source

No, you cannot do this. It will only show indexes. Also, for looping for an array in JavaScript is bad practice. It will go through the entire array object method.

+3
source

Massive methods forEach , map , filter , etc. will iterate over the literal indexes of the array:

 ['dog', 'cat', 'cow'].forEach(alert); 

Gasket for older browsers:

 if(![].forEach){ array.prototype.forEach= function(fun, scope){ var T= this, L= T.length, i= 0; if(typeof fun== 'function'){ while(i< L){ if(i in T){ fun.call(scope, T[i], i, T); } ++i; } } return T; } } 
+2
source

The wrong syntax construct is used for this.

for in intended to enumerate the properties of an object, and not to iterate through arrays. Declare your array outside and use a regular loop.

 var arr = ['dog', 'cat', 'cow']; for(var i = 0; i < arr.length; i++) { // your code } 
+1
source

All Articles