typescript 将1D数组和变量转换为新的2D数组

cvxl0en2  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(153)

我是编程新手,我在 typescript 中与数组作斗争。我有以下变量:

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

我的目标是创建一个新的2D数组: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;
    }

有人能帮我吗?非常感谢!

qnyhuwrf

qnyhuwrf1#

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

相关问题