简体   繁体   English

使用遍历 2 个数组的循环将键/值添加到空对象中

[英]Adding keys / values into a empty object using a loop that iterates over 2 arrays

You are given an array of names along with an array of phone numbers.您将获得一组姓名以及一组电话号码。 Using a loop, populate the existing phoneBook object to build a proper phonebook with the keys being people's names and the values being their respective phone numbers.使用循环,填充现有的 phoneBook 对象以构建一个合适的电话簿,键是人们的姓名,值是他们各自的电话号码。

I don't know where to begin I am fairly new on how to add keys : values using a loop from an array into an object我不知道从哪里开始我对如何添加键还很陌生:使用从数组到对象的循环的值

const phoneBook = {


};

for (let i = 0; i < names.length; i++) for (let i = 0; i < names.length; i++)

const names = ['Mira', 'Royce', 'Kathie'];

const numbers = ['3234958675', '9164059384', '4154958675']

console.log(phoneBook["Mira"]); //=> 3234958675

console.log(phoneBook["Royce"]); //=> 9164059384

console.log(phoneBook["Kathie"]); //=> 4154958675

I am getting undefined obviously as I haven't figured out how to get the loop to populate the object from the names and numbers arrays我显然未定义,因为我还没有弄清楚如何让循环从名称和数字数组中填充对象

You can loop over names and their indices (with a forEach loop), and get the appropriate number from the numbers array (using the index):您可以遍历名称及其索引(使用forEach循环),并从 numbers 数组中获取适当的数字(使用索引):

 const phoneBook = {}; const names = ['Mira', 'Royce', 'Kathie']; const numbers = ['3234958675', '9164059384', '4154958675'] names.forEach( (name, i) => phoneBook[name] = numbers[i] ); console.log(phoneBook["Mira"]); //=> 3234958675 console.log(phoneBook["Royce"]); //=> 9164059384 console.log(phoneBook["Kathie"]); //=> 4154958675

for (let i = 0; i < names.length; i ++){ let name = [] name.push(names[i]) phoneBook[name] = numbers[i] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM