What for .... in statement in javascript

anyone can explain how to use for ... in an instruction in javascript. I read the w3school article, but I think this is not so clear. Below is the code, please explain this:

<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[10] = "Saab";
mycars[20] = "Volvo";
mycars[30] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
+3
source share
4 answers

A for inloop will go through each property of the object.

In your example, the variable xwill loop through each property in the object mycars.

If you add mycars.expensive = "Porsche";, it will also detect this.


Note that, as indicated by MDC , loops for inshould not be used to loop through regular arrays:

Array, . for...in , (, "foo" Array.prototype), for...in . , , . , for , . ... ( propertyIsEnumerable() hasOwnProperty() ), Object.prototype(, , , Array.prototype, , , , , ... in).

+6

( )

  var mycars = new Object();
  mycars[10] = "Saab";
  mycars[20] = "Volvo";
  mycars[30] = "BMW";

10, 20 30 - .
, , .

[for ( in object]]. javascript :
​​ , , .

  for (v in mycars) alert(v);

, ,

  for (v in mycars) alert("Property: "+v+", value: "+mycars[v]);
+1

for ... in in. for mycars.

0

for in - . , , , , . , hasOwnProperty.

It’s better to use an infrastructure feature like jQuery $.each

0
source

Source: https://habr.com/ru/post/1782709/


All Articles