将一个一维数组和一个变量转换为一个新的二维数组。

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

Turning a 1D array and a variable into a new 2D array

问题

我是新手程序员,对 TypeScript 中的数组感到困惑。
我有以下变量:

let nameList: string[] = ['a', 'b', 'c', 'd'];
let postId: number = 1;

我的目标是创建一个新的二维数组:
let newList: (string | number)[][] = [];

其中

newlist = [
      [a,1],
      [b,1],
      [c,1],
      [d,1]
    ]

我尝试过:

for (let i: number = 0; i < userList.length; i++) {
      newList[i][0].push(userList[i]);
      newList[i][1].push(insertID);
    }

还尝试过

for (let i: number = 0; i < userList.length; i++) {
      newList[i][0] = userList[i];
      newList[i][1] = insertID;
    }

有人能帮我解决这个问题吗?
非常感谢!

英文:

Im new to programming and Im struggling with arrays in typescript.
I have the following variables:

let nameList: string[] = ['a', 'b', 'c', 'd'];
    let postId: number = 1;

My goal is to create a new 2D array:
let newList: (string | number)[][] = [];

where

newlist = [
      [a,1],
      [b,1],
      [c,1],
      [d,1]
    ]

I've tried:

for (let i: number = 0; i < userList.length; i++) {
      newList[i][0].push(userList[i]);
      newList[i][1].push(insertID);
    }

Also

for (let i: number = 0; i < userList.length; i++) {
      newList[i][0] = userList[i];
      newList[i][1] = insertID;
    }

Can someone help me with this?
Much apprerciated!

答案1

得分: 0

const new2dArray: [string, number][] = nameList.map((name) => [name, postId]); 的中文翻译是:

const new2dArray: [string, number][] = nameList.map((name) => [name, postId]);

英文:

const new2dArray: [string, number][] = nameList.map((name) => [name, postId]);

huangapple
  • 本文由 发表于 2023年4月19日 17:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052761.html
匿名

发表评论

匿名网友

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

确定