如何通过两个数组迭代并将键值返回到其他对象
const phoneBook = {};
const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675']
function populate(names, numbers) {
for(i = 0; i < populate.length; i++) {
phoneBook[names[i]] = numbers[i];
}
}
如何同时使我的for循环通过两个阵列迭代并返回名称作为键和数字作为值?
const phoneBook = {};
const names = ['Mira', 'Royce', 'Kathie'];
const numbers = ['3234958675', '9164059384', '4154958675']
function populate(names, numbers) {
for(i = 0; i < populate.length; i++) {
phoneBook[names[i]] = numbers[i];
}
}
How can I get my for loop to iterate through both arrays simultaneously and return names as a key and numbers as the values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的想法大多是正确的。
两个建议:
numbers.length
或names.length
作为您可能不想改变全局对象一个工作示例看起来像是这样像这样:
You mostly have the right idea.
Two suggestions:
numbers.length
ornames.length
as the number of iterationsA working example would look something like this:
更简洁地说,将数组压缩在一起,然后将其传递给
Object.fromEntries(0
More concisely, zip the arrays together, then pass that to
Object.fromEntries(0
只是说明, lodash 如果不这样头脑:
而且,当然是单线:
Just for the note, lodash if you don't mind:
And, of course, one-liner: