简体   繁体   中英

What Is The Meaning Of This JS DOM Code?

I found this function to find the JS DOM methods. However, I couldn't understand the logic behind it.

for (var l in document.body){
  console.log("document."+l+":"+document.body[l]);
}

What does the var 1 mean? It seems, document.body is an array and we are iterating over the array. However, something seems strange. In the above code, when I insert spaces around "1" and ":" inside the for loop, it's showing different results. (It is adding the "1" as a string.) And without the spaces, it is returning the property and method names.

Can someone please break down the meaning of the code to me? Thanks.

This is a for ... in loop .

What does the var 1 mean?

Each time you go around the loop, a different property of the object ( document.body ) is assigned to the variable l (which is a lowercase L not the numeral one).

Replacing the variable name with a string will use the literal value of that string instead of the property name.

iterating over the array

It isn't an array, it is an object (more specifically an HTML body element object ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM