Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  136] [ 3]  / answers: 1 / hits: 22004  / 8 Years ago, fri, july 29, 2016, 12:00:00

this is a very common usage of javascript or typescript foreach:



myArray = [a,b,c]

for(var index in myArray)
console.log(myArray[index])


the code logs: a b and c



However in typescript the index var is considered to be a string. .
When I make any calculations, for instance index*2, the TS compuler shows the fallowing compiler error:



for(var index in myArray)
console.log(index * 2); // TS compiler error.



Error TS2362 The left-hand side of an arithmetic operation must be of
type 'any', 'number' or an enum type




but logs 0,2 and 4 when executed (as expected)



How can I avoid or suppres this error?


More From » foreach

 Answers
6

index is a string. for..in iterates over the keys of an object. It just so happens that the keys of an array are numerical. Still, they're stored as strings.



Check this out:





var myArray = [1, 2, 3];
for (var index in myArray) {
console.log(typeof index);
}





It's also worth noting that there's no guarantees about the order that you'll get those keys. Usually they'll appear in the right order but it would not be invalid for you to get 3, 1, 2, for example.



Instead, just use a normal for loop. Then your indices will be numbers and you'll know for sure that you're moving through the array in order.





var myArray = [1, 2, 3];
for (var i = 0; i < myArray.length; i++) {
console.log(typeof i, myArray[i]);
}





You could also run through it using forEach.





var myArray = [1, 2, 3];
myArray.forEach(function(val, index) {
console.log(typeof index, val);
});




[#61203] Wednesday, July 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;