我已经问过5-6个问题了,所以在询问_之前,其他问题似乎是指格式化来自完整JSON文件的所有数据。这个问题是关于格式化从JSON文件_解析的数组的元素。
完整的测试页面是在线的这里,但为了简洁起见,我缩短了JSON _
{
"PGRgames" : [
{
"id" : "Abzu",
"fullName" : "Abzû",
"PEGI" : 7,
"platforms" : ["PS4"],
"genres" : ["Adventure", "Simulation"],
"image" : "img_Abzu.png",
"details" : "ABZÛ is a beautiful underwater adventure that evokes the dream of diving. Immerse yourself in a vibrant ocean world full of mystery and bursting with colour and life."
},
{
"id" : "AdventurePirates",
"fullName" : "Adventure Time: Pirates Of The Enchridion",
"PEGI" : 7,
"platforms" : ["XBoxOne", "PS4", "Switch"],
"genres" : ["Adventure", "Sandbox", "KIDS"],
"image" : "img_AdventurePirates.png",
"details" : "The Land of Ooo is underwater and it’s up to Finn and Jake to find out why. Join our heroes as they explore the high seas."
},
{
"id" : "KingdomCome",
"fullName" : "Kingdom Come: Deliverance",
"PEGI" : 18,
"platforms" : ["XBoxOne", "XBoxOneX", "PS4"],
"genres" : ["Action", "RPG"],
"image" : "img_KingdomCome.png",
"details" : "Massive realistic open world: Majestic castles, vast fields, all rendered in stunning high-end graphics. Solve quests in multiple ways, then face the consequences of your decisions."
}
]
}我的JS代码是_
<script>
let askHTTP = new XMLHttpRequest();
askHTTP.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let gamesList = JSON.parse(askHTTP.responseText);
let output = '';
let PGRgames = gamesList.PGRgames;
for (let i = 0; i < PGRgames.length; i++) {
output += '<div class="col-md-3 col-sm-6 padBox"><div class="gameBox center"><img src="media/'
+ PGRgames[i].image
+ '" /><div class="horizBuffer"></div>'
+ '<div class="center"><span class="fontBrand1 smallText"><strong>' + PGRgames[i].genres + '</strong></span></div>'
+ '<div class="horizBuffer"></div>'
+ '<div class="left"><span class="fontBlack text">' + PGRgames[i].details + '</span></div>'
+ '<div class="horizBuffer"></div>'
+ '<div class="center"><span class="fontBlack text"><strong>' + PGRgames[i].platforms + '</strong></span></div>'
+ '</div></div>';
}
document.getElementById('displayGames').innerHTML = output;
}
};
askHTTP.open("GET", "js/PGRgames.json", true);
askHTTP.send();
</script>如果您查看我链接到的页面上的内容,您将看到PGRgames.genres & PGRgames.platforms有逗号,但是数组元素之间没有空格,而且数组不符合它们应该限制在_的区域。
格式化这两个数组是我的问题所指的--我非常感谢您的任何帮助:)
发布于 2019-04-27 15:37:32
可以使用.join()将数组格式化为字符串。
var array = ["foo", "bar", "tet"];
console.log('formatted:', array.join(', '));
console.log('tostring:', ''+array);
在您的示例中,以类似的方式将PGRgames[i].genres替换为PGRgames[i].genres.join(', ')和其他数组输出。
发布于 2019-04-27 15:46:45
你的问题是你写了这行:
PGRgames[1].platforms这就像是在写:
PGRgames[1].platforms.toString()它所做的就是使用数组中每个元素的tostring并将它们与逗号连接起来。
您需要做的是使用join对tha数组进行格式设置,如下所示:
PGRgames[1].platforms.join(', ')https://stackoverflow.com/questions/55882073
复制相似问题