我在 javascript 变量中有 json 字符串。我想从 JSON 字符串中获取随机值并设置为 HTML。
var jsonContent= {
"featured": [
{
"id": "111",
"title": "post title 111",
"desc": "This is a test desc 111"
},
{
"id": "222",
"title": "post title 222",
"desc": "This is a test desc 222"
},
{
"id": "333",
"title": "post title 333",
"desc": "This is a test desc 333"
}
]
};
例如,像这样将第一个键值分配给我的 html:-
<div class="r-v-details">
<span class="r-v-title">post title 111</span>
<span class="r-v-description">This is a test desc 222</span>
</div>
如何从 JSON 字符串中获取随机键值?我是否需要将 JSON 解析为数组然后才能获得随机值?或者我只能通过 json 来实现? 你能建议我吗?
最佳答案
应该是:(在控制台查看结果)
var jsonContent = {
"featured": [
{
"id": "111",
"title": "post title 111",
"desc": "This is a test desc 111"
},
{
"id": "222",
"title": "post title 222",
"desc": "This is a test desc 222"
},
{
"id": "333",
"title": "post title 333",
"desc": "This is a test desc 333"
}
]
}
var random = jsonContent.featured[Math.floor(Math.random() * jsonContent.featured.length)];
console.log(random)
关于javascript - 如何在 JSON 中获取随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589598/