I'm parsing a string to a float, and when I print the type of the variable, I get number. However, if I add the variable to an array, and print it from there, I get string. But if I then index clicks[0], I once again get number
let clicks = []
let latitude = parseFloat(stringCoords.substring(11, 28))
clicks.push(latitude)
console.log(typeof(latitude)) -- prints number
for (var object in clicks) {
console.log(typeof(object)) -- prints string
}
console.log(typeof(clicks[0])) -- prints number
The only thing I'm adding to the clicks array is the latitude variable. I'm confused as to why it's changing types. Please let me know.
CodePudding user response:
The for..in loops through the properties of an object which has the type string
. And for..of loops through the values of an iterable object, which has the type of whatever you store in it (In your case, a number).
let clicks = []
let latitude = parseFloat("10.33")
clicks.push(latitude)
console.log(typeof(latitude))
for (var object of clicks) {
console.log(typeof(object))
}
console.log(typeof(clicks[0]))
CodePudding user response:
as 'for(... in ...)' you are navigating through an array, 'object' actually produces the index value of that element, not the element of the current array. When you navigate with the 'clicks.forEach(...)' structure, you access the elements of the array. Therefore, you get a "string", so the operation you do with "typeof(...)" is not on the same elements. One of them gives the array index and the other gives the element of the array.