如何创建一个强类型数组的数组?

huangapple go评论76阅读模式
英文:

How to create an array of strongly typed arrays?

问题

I tried to write such simple code:

let arr: Array<[string, number]> = ['dad\'s adidas', 123], ['moms gucci', 47];

for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
    }
    console.log('\n');
}

但编译器报错并显示以下错误:

Uncaught SyntaxError C:\Users\sv25b\UbuntuProjects\WTF\main.ts:1
let arr: Array<[string, number]> = ['dad\'s adidas', 123], ['moms gucci', 47];

我做错了什么?

英文:

I'm new in TS, but i didn't find answer for my question, so that's why I'm here)

I'm trying to create an array of arrays, that may contain only strongly typed data. For example like [[string, number], [string, number], [string, number], ...]

I tried to write such simple code:

let arr: Array&lt;[string, number]&gt; = [[&#39;dad\&#39;s adidas&#39;, 123], [&#39;moms gucci&#39;, 47]]

for (let i = 0; i &lt; arr.length; i++) {
    for (let j = 0; i &lt; arr[i].length; j++) {
        console.log(arr[i][j])
    }
    console.log(&#39;\n&#39;)
}

but the The compiler swears and give me this stupid error))

Uncaught SyntaxError C:\Users\sv25b\UbuntuProjects\WTF\main.ts:1
let arr: Array&lt;[string, number]&gt; = [[&#39;dad\&#39;s adidas&#39;, 123], [&#39;moms gucci&#39;, 47]]

What did I do wrong?

答案1

得分: 0

  1. 运行 npm install tsx - 安装 typescript runner
    • 或者全局安装它,使用 npm install --global tsx
  2. 运行 npx tsx watch main.ts 以在监视模式下运行您的文件(在文件保存时重新启动)
  3. 查看您的代码无限记录 undefined
  4. 修复 i &lt; arr[i].lengthj &lt; arr[i].length
英文:
  1. run npm install tsx - install typescript runner
    • or install it globally with npm install --global tsx
  2. run npx tsx watch main.ts to run your file, in watch mode (restarting on file save)
  3. see that your code infinitly logs undefined
  4. fix i &lt; arr[i].length to j &lt; arr[i].length

huangapple
  • 本文由 发表于 2023年4月10日 20:47:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定