0

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.

4
  • 1
    object is the array index, not the array element. Commented Dec 27, 2021 at 5:24
  • 2
    Use for-of to loop over array elements. Commented Dec 27, 2021 at 5:25
  • Why didn't you try console.log(object)? You would have seen the problem immediately. Commented Dec 27, 2021 at 5:25
  • As for why: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… explains the problems with for...in when using Array, which is what you're doing here. Commented Dec 27, 2021 at 5:26

2 Answers 2

1

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])) 

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.