I have the following problem with a 'for in' loop: it doesn't want to recognize the elements of the array. I tried to see the elements after calling 'for in' with the console.log , but it returns 0 .
function isValidWalk(walk) {
console.log(walk.length);
if (walk.length ===10) {
var WalkN=[];
var WalkS=[];
var WalkE=[];
var WalkW=[];
console.log(walk);
for (var elemento in walk) {
console.log(elemento);
console.log(walk);
switch (elemento) {
case 'n':
WalkN.push(elemento);
break;
case 's':
WalkS.push(elemento);
break;
case 'e':
WalkE.push(elemento);
break;
case 'w':
WalkW.push(elemento);
}
console.log( WalkN,WalkS,WalkE,WalkW);
if (WalkN.length===WalkS.length && WalkE.length===WalkW.length) {
return true
}
else { return false }
}
}
else {
return false
}
}
isValidWalk(['n','s','n','s','n','s','n','s','n','s'])
The problem is that
for..in
it is not designed for arrays but for objects. To object to the result you want, it's better to useforEach
like this:You can do it this way too:
The easiest way to have what you want in a foreach loop is to change the
for
in such a way that it would be almost as is as you have it.
that way you can access the content of the array and not the index.