1

I have an array. As far as I know array keys are integers in javascript.

const array1 = ['a', 'b', 'c']; 

When I get and log keys I get an array of integers.

console.log([...array1.keys()]);

// Outputs=>  [0, 1, 2]

But in a for...in loop keys are string. But why and is there a way to type cast for integer keys?

for (const key in array1) {
  console.log("Type of key "+key+" is "+ typeof key);
}

/* outputs:
Type of key 0 is string
Type of key 1 is string
Type of key 2 is string
*/

Zortext
  • 566
  • 8
  • 21

3 Answers3

4

But why and is there a way to type cast for integer keys?

Arrays are really just objects.
Array elements are just object properties whose keys are their respective indexes.
Property keys are always either string values or symbol values.

You can cast any string to a number using the Number function or the unary plus operator:

Number("5")
+"5"

However you should probably avoid using for...in to iterate over arrays.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You can use parseInt() function to cast string value to interger,

Ex:

parseInt("1"); //return 1
Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
1

//actually the for in loop is used for objects , as the key in objects is always assigned as string whether you put a string or not

const obj = {a:1,b:2}
for (key in obj){
    console.log('typeof ',key,' is ',typeof key)
    console.log('valueof ',key,' is ',obj[key])
}
 
// Now because you used array the keys are indexes of the array so there for 0, 1, 2 .. and so on are logged as string not integers 
 
 //to solve this problem
 
const array = ['a','b','c']

//1. one can use the for each loop and used the index in the parameter

array.forEach((elem,index) => {
    console.log(elem,' ',index)
});

console.log(`2. use a for range loop`)

for (let i = 0; i < array.length; i++) {
    console.log(array[i],i)
}

//3. using the same for key loop convert the key into index

for (const key in array) {
    console.log("Type of key "+Number(key)+" is "+ typeof Number(key));
  }
Shreyansh Gupta
  • 382
  • 1
  • 10