JS显示对象和每个

时间:2016-06-12 23:12:18

标签: javascript arrays object properties

所以新手尝试了解Javascript的早期步骤。我试图了解对象数组以及如何显示对象及其属性。例子是显示水果的颜色:

var fruitColor = {'apples':'red', 'bananas':'yellow', 'grapes':'purple'};


//answer would be string and then the properties...
//"Color of fruit: apples - red, bananas - yellow, grapes - purple"

1 个答案:

答案 0 :(得分:1)

类似的东西:

var fruitColor = {'apples':'red', 
                  'bananas':'yellow', 
                  'grapes':'purple'
                  };
var sentence="Color of fruit: ";
for(var fruit in fruitColor){
    sentence+= fruit + " - " + fruitColor[fruit] + ", ";
}
sentence=sentence.substring(0, sentence.length - 2); 
// remove the last ','

查看for...in循环

https://jsfiddle.net/n0z13ge6/