Why is the array index a string in the code below?

var arrayOfNumbers=[1,2,3,4,5,6,78];
for(var index in arrayOfNumbers){
   console.log(index+1);
}
Run codeHide result

The output for this sample code.
01
11
21
31
41
51
61

Why in Javascript is this array index considered as a string?

+4
source share
6 answers

From MDN to ... to

Note: for ... in should not be used to iterate over an array where the index value is important.

... The for ... in statement of the loop returns all enumerated properties, including those with non-integer names and those that are inherited.

When used for ... there is always a string in the key, and all it does is concatenate the strings.

, Array.foreach() :

var arrayOfNumbers=[1,2,3,4,5,6,78];
arrayOfNumbers.forEach(function(item, index){
     console.log(index + 1); // here the index is a number!
});
Hide result
+2

- , object.In java script , .

, int +.

var arrayOfNumbers=[1,2,3,4,5,6,78];
for(var index in arrayOfNumbers) {
  var v = parseInt(index) + 1;
  console.log(v);
}

var arrayOfNumbers=[1,2,3,4,5,6,78];
for(var index in arrayOfNumbers) {
  var v = parseInt(index) + 1;
  console.log(v);
}
Hide result
 var arrayOfNumbers=[1,2,3,4,5,6,78];
 for(var index in arrayOfNumbers){
    var v = +index + 1;
     console.log(v);
  }
0

// in // , , :

arr={
"0":1,
"1":2,
"2":3,
"3":4,
"4":5,
"5":6,
"6":78
}

//, .

var arrayOfNumbers=[1,2,3,4,5,6,78];
  for(var index=0;index<arrayOfNumbers.length;index++){
       console.log(index+1);
   }
0

MDN FOR..IN

for... in . .

var string1 = "";
var object1 = {a: 1, b: 2, c: 3};

for (var property1 in object1) {
  string1 = string1 + object1[property1];
}

console.log(string1);
Hide result

, t : { foo : 'something in universe'}

,

var arrayOfNumbers=[1,2,3,4,5,6,78];
  for(var index in arrayOfNumbers){
       console.log(arrayOfNumbers[index+1]);
   }
   console.log(arrayOfNumbers)
Hide result
0

, for , javascript . , . - :

var arrayOfNumbers=[1,2,3,4,5,6,78];
arrayOfNumbers.forEach(function(num)
{
    console.log(num+1);
});
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for... in .

, index . .

In addition, a Stringplus a Numberis equal to a String, which is printed in console.

0
source

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


All Articles