参见英文答案 > When iterating over values,why does typeof(value) return “string” when value is a number? Javascript 1个
var arrayOfNumbers=[1,2,3,4,5,6,78];
for(var index in arrayOfNumbers){
console.log(index+1);
}
为什么在Javascript中这些数组索引被视为字符串?
最佳答案
@H_404_21@从MDN for…in起
Note: for…in should not be used to iterate over an Array where the index order is important.
… The for…in loop statement will return all enumerable properties,
including those with non–integer names and those that are inherited.
当在键中使用for …时总是一个字符串,它所做的只是字符串连接.
你有一个数组,所以最好像这样使用Array.foreach():
var arrayOfNumbers=[1,78];
arrayOfNumbers.forEach(function(item,index){
console.log(index + 1); // here the index is a number!
});