如何创建和更改数组中的颜色

时间:2019-05-06 01:57:30

标签: javascript json

我是javascript的新手,试图了解w3school的json数组是如何工作的,但是没有运气。我的目标是创建一个json,在单击屏幕上的按钮后,显示如下所示的信息列表。(很抱歉,如果第一篇文章的格式不正确,则很抱歉。)

名称:Tim
最喜欢的颜色:蓝色
家庭住所:Livington Road 111。

名称:Sara
最喜欢的颜色:粉红色
家庭地址:学习路222号。

等...

我希望此人的文本名称具有其喜欢的颜色。如果我列出了4个不同颜色的人。

var myObj, i, j, x="";    
myObj = {
  "name": ["Tim","Sara","John","Billy"
  "Favorite_Color":"Blue","Pink","Yellow","Green"
  "Address": "111 Livington Road","222 Learning Road","333 JavaScript 
Lane","444 I'm lost road"}

for (i in myObj.name){
x += "<h2> + myObj.name[i] + "</h2>";
  for (j in myObj.name[i].favorite_colors) {
   x += myObj.name[i].favore_colors[j]; }
}

链接到我正在寻找的大致图像

Link to an image of roughly what I am looking for:

1 个答案:

答案 0 :(得分:0)

我想的对象应该是

myObj = {
    name: ["Tim","Sara","John","Billy"],
    Favorite_Colors: ["Blue","Pink","Yellow","Green"],
    Address: ["111 Livington Road","222 Learning Road","333 JavaScript Lane","444 I'm lost road"]
}

您可以在myObj.name上循环播放,并通过index得到该人的Favorite_colors,如下所示:

let x = '';
myObj.name.forEach(function(name, index){
    x += '<h2 style="color: ' + myObj.Favorite_Colors[index] + '>"' + name +'</h2>'
});

但是,让我添加一条建议,您可以将myObj重组为:

myObj = [
    {name: 'Tim', favoriteColor: 'blue', address: '111 Livington Road'},
    {name: 'Sara', favoriteColor: 'Pink', address: '222 Learning Road'},
    {name: 'John', favoriteColor: 'Yellow', address: '333 JavaScript Lane'},
    {name: 'Billy', favoriteColor: 'Green', address: '444 I\'m lost road'},
]

这是一个对象数组,然后我们可以轻松地在每个对象上循环(无需使用索引),如下所示:

let x = '';
for (let item of myObj) {
    x += '<h2 style="color: ' + item.favoriteColor + '">' + item.name +'</h2>'
}