0

I have a question about for loop in js, here are examples:

In this part, child is object (what I want).

for (var i = 0; i < element.childNodes.length; i++) {
        var child = element.childNodes[i];
        console.log(typeof(child));
}

But when change the code, child become to String, valued 0, 1, 2 ...

for (var child in element.childNodes) {
        console.log(typeof(child));
}

Why the two types of for loop got different results? Thanks..

hfawja
  • 43
  • 6
  • 2
    the second loop is looping through the keys. To obtain similar result you would need `element.childNodes[child]` – maioman Oct 09 '17 at 14:34
  • 1
    because the `for..in` loop iterates the enumerable keys of an object. Like `for(var key in object) ...`. you probably meant `for(var child of element.childNodes) ...` – Thomas Oct 09 '17 at 14:34
  • 1
    You should use `of` instead of `in` – Karan Desai Oct 09 '17 at 14:35
  • 1
    Why did you not use the `for (var i in element.childNodes) { var child = element.childNodes[i]; … }` pattern in the second snippet as well? – Bergi Oct 09 '17 at 14:43

2 Answers2

0

"A for...in loop only iterates over enumerable properties." Check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Said properties are just strings which i believe are the keys in your object.

davidchoo12
  • 1,261
  • 15
  • 26
-1

In a for in loop, you retrieve keys. The following should log the same as your first loop:

for (var child in element.childNodes) {
  console.log(typeof(element.childNodes[child]));
}
Meldon
  • 730
  • 2
  • 6
  • 13