javascript 如何在 JSON 中获取随机值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19589598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:05:32  来源:igfitidea点击:

How to get random values in JSON

javascriptjqueryjson

提问by prakashapkota

I have json string in javascript variable . I want to get random value from JSON string and set into HTML.

我在 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"
            }
    ]
};

for e.g first key value assign to my html like this:-

例如,像这样分配给我的 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>

How can I get random key values from JSON string? Does I need to parse JSON into array then I can get random value? or I can achieve this by json only? Can you please suggest me.

如何从 JSON 字符串中获取随机键值?我是否需要将 JSON 解析为数组然后才能获得随机值?或者我只能通过 json 来实现?你能建议我吗。

回答by Vicky Gonsalves

It should be: (check result in console)

它应该是:(在控制台中检查结果)

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)

回答by prakashapkota

Try this:

试试这个:

var random = jsonContent["featured"][Math.floor(Math.random()*jsonContent["featured"].length)];