gpt4 book ai didi

javascript - 我可以使用 for 循环吗? or 函数和 make 对于这个数组来说是最短的和动态的

转载 作者:行者123 更新时间:2023-11-29 17:42:30 26 4
gpt4 key购买 nike

我是新来的,想在这里学习,所以我想向大家了解一些信息和学习。我们可以为此语句或 if 语句使用 ForEach 吗??

    var people = [
[1, 'Dimitri', 'Microsoft'],
[2, 'Mike', 'Microsoft'],
[3, 'John', 'Microsoft']
];


var people2 = `ID : ${people[0][0]}`;
var people3 = `NAME : ${people[0][1]}`;
var people4 = `COMPANY : ${people[0][2]}`;
console.log(people2);
console.log(people3);
console.log(people4);

var people5 = `ID : ${people[1][0]}`;
var people6 = `NAME : ${people[1][1]}`;
var people7 = `COMPANY : ${people[1][2]}`;
console.log(people5);
console.log(people6);
console.log(people7);

var people8 = `ID : ${people[2][0]}`;
var people9 = `NAME : ${people[2][1]}`;
var people10 = `COMPANY : ${people[2][2]}`;
console.log(people8);
console.log(people9);
console.log(people10);

最佳答案

您可以使用一个数组来描述所需的内容,并获取相应索引的数组的值。

var people = [[1, 'Dimitri', 'Microsoft'], [2, 'Mike', 'Microsoft'], [3, 'John', 'Microsoft']],
keys = ['ID', 'NAME', 'COMPANY'];

people.forEach(a => keys.forEach((k, i) => console.log(`${k} : ${a[i]}`)));
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果你想获得具有名称属性的对象,你可以使用short hand properties

var people = [[1, 'Dimitri', 'Microsoft'], [2, 'Mike', 'Microsoft'], [3, 'John', 'Microsoft']];

console.log(people.map(([ID, NAME, COMPANY]) => ({ ID, NAME, COMPANY })));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 我可以使用 for 循环吗? or 函数和 make 对于这个数组来说是最短的和动态的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52299474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com