gpt4 book ai didi

javascript - 将数组的索引插入一个对象

转载 作者:行者123 更新时间:2023-11-28 05:18:28 25 4
gpt4 key购买 nike

如何将数组索引推送到一个对象中,在我的示例中,{key:value} 之间的对应关系是 {authors[i]: quotes[i]}

请检查我的代码笔:

http://codepen.io/anon/pen/Ndezeo

谢谢。

最佳答案

您可以迭代 authors 并将名称作为键并将 quotes 的项目分配为对象的属性。

var quotes = [], 
authors = [],
object = {};

quotes[0] = "I have a new philosophy. I'm only going to dread one day at a time.";
authors[0] = "Charles Schulz";
quotes[1] = "Reality is the leading cause of stress for those in touch with it.";
authors[1] = "Jack Wagner";
quotes[2] = "Few things are harder to put up with than the annoyance of a good example.";
authors[2] = "Mark Twain";
quotes[3] = "The pure and simple truth is rarely pure and never simple.";
authors[3] = "Oscar Wilde";
quotes[4] = "There's no business like show business, but there are several businesses like accounting.";
authors[4] = "David Letterman";
quotes[5] = "Man invented language to satisfy his deep need to complain.";
authors[5] = "Lily Tomlin";

authors.forEach(function (k, i) {
object[k] = quotes[i];
});

console.log(object);

关于javascript - 将数组的索引插入一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42210834/

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