数组索引字符串或数字的类型



当我在数组的索引上循环时,它们显示为字符串。但是禁止使用字符串对数组进行索引。这不是语无伦次吗?为什么会这样?

for (const i in ["a", "b", "c"]) {
console.log(typeof i + " " i + " " + arr[i]);  // -> string 0 'a', etc.
}
arr['0'] // ERROR ts7105: Element implicitly has an 'any' type because index expression is not of type 'number':

for ... in迭代给定对象的键。

数组将其索引作为关键字,请参见打印["0", "1", "2"]Object.keys([4,5,1])。要迭代类型化数组,请使用for ... of请参阅文档。如果需要索引,请使用常规的for(let i=0;i<arr.length;i++)for(let [i,el] of arr.entries())循环。

至于你的问题,是的,它看起来确实不连贯,但看起来像是在循环中使用循环变量进行索引允许字符串索引。但是要注意,index + 1将是"01",因为索引是一个字符串。

最新更新