英文:
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]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论