Suppose I have a array like that:
let array = [1, 45, 14, 4]
When I look for the type of these integers I get a number type (Normal: Exactly what i expected )
Now suppose that I declare my array like that :
let array = [].push(1) or [].concat([1,2,3])
Now, If I try to get the type with "typeof", I get a type of string
In the snippets below all integers in an array are of string types. I do not understand why!
PS: I need the types to be strict
var array = [1,2,3,4,5]; for (item in array) { console.log(typeof item); }
They are numbers
var array = [1,2,3,4,5]; array.push(6); array = array.concat([7,8,9]) for(var i = 0; i < array.length; i++) { console.log(typeof array[i]) }
And if you check the item
's value in your sample, you'll see it is not the array items, it is their index, which is how for/in
works when iterate an object (which an array actually is too)
var array = [1,2,3,4,5]; for(item in array) { console.log(typeof item, "type, and item value is: " + item) }
Here for..in loop iterates over keys and it is the index of element in string format. Hence the type here is string for each element's key.
While typeof array element is obviously number. Check it in below code:
var array = [1,2,3,4,5]; for(item in array) { console.log(typeof item, item, typeof array[item], array[item]) }
You made small mistake, for(i in arr)
giving you not item but index
var array = [1, 2, 3, 4, 'a']; for(idx in array){ //console.log(typeof array[i]) console.log('index:'+idx+ ' item:'+array[idx]+ ' typeof:'+typeof array[idx]) }
Or you can use for loop like that to have directly access to item:
var array = [1, 2, 3, 4, 'a']; for (var idx = 0; idx < array.length; idx++) { console.log(array[idx]+':'+typeof array[idx]) }
Third option is to use forEach():
var array = [1, 2, 3, 4, 'a']; array.forEach( item=> console.log(item+':'+typeof item) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.