首页 > 解决方案 > 数组索引字符串或数字的类型?

问题描述

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

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':

标签: typescript

解决方案


for ... in遍历给定对象的键。

一个数组将它的索引作为键,看看Object.keys([4,5,1])哪个打印["0", "1", "2"]。要迭代类型化数组,请使用for ... of See the docs。如果您需要索引,请使用常规for(let i=0;i<arr.length;i++)for(let [i,el] of arr.entries())循环。

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


推荐阅读