typescript - 数组索引字符串或数字的类型?
问题描述
当我遍历数组的索引时,它们显示为字符串。但是禁止使用字符串索引数组。这不是语无伦次吗?为什么会这样?
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
遍历给定对象的键。
一个数组将它的索引作为键,看看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"
因为索引是一个字符串。
推荐阅读
- excel - 基于多个标准的值计数
- python - 显示 RTSP 媒体流和读取键盘输入/发送 Telnet 命令时出现延迟
- sql-server - SSIS 使用 SSIS 表达式将 mmddyyyy 格式的日期转换为日期格式
- kubeflow-pipelines - Kubeflow 处理大型输入文件时出错:节点资源不足:临时存储
- r - R:使用重复()时重复的错误值
- go - 对 Go 中的某些数据结构语法感到困惑
- android - Cordova webview 中的 Google Pay 导致“意外的开发人员错误,请稍后重试”。错误
- python - 将第一个值转换为 np.nan
- c - 将inotify“事件”的对象保存在c中的数组中
- powershell - Powershell Script,在不知道电子邮件地址的情况下向脚本用户发送电子邮件(通过 Outlook)