使用 jQuery 和 Math.random() 选择嵌套对象属性

Lew*_*wie 5 javascript random jquery javascript-objects

我正在创建一个随机报价机,它将显示来自不同哲学家的随机报价。

我有一个包含哲学家及其引号的嵌套对象的对象文字。使用 jQuery 函数和 Math.random(),如何从对象文字结构中选择随机引号?有没有更好的方法来组织数据?

我从一个 jQuery 闭包开始,它会显示一个我想使用 Math.random() 修改的指定引用。

由于我是初学者,因此正在寻找解决方案的解释。提前致谢。

示例对象字面量:

var quotes = 
{
  awatts: {
    name: "Alan Watts",
    quote: "The only way to make          sense out of change is to            plunge into it, move with it,        and join the dance."
  },
  etolle: {
    name: "Eckhart Tolle",
    quote: "Realize deeply that the       present moment is all you ever       have."
  },
  tmckenna: {
    name: "Terrence Mckenna",
    quote: "“The cost of sanity in        this society, is a certain          level of alienation” "
  }
};
Run Code Online (Sandbox Code Playgroud)

选择单引号的示例 jQuery 函数:

    $(document).ready(function() {
        $('.mybutton').click(function() {
            $('#quote').html(quotes.awatts.quote);
        });
    });
Run Code Online (Sandbox Code Playgroud)

ade*_*neo 2

数据的结构看起来不错。您可以使用数组,但对象不是问题。

\n\n

您将从对象中获取密钥,然后选择一个随机密钥

\n\n

\r\n
\r\n
var quotes = {\r\n  awatts: {\r\n    name: "Alan Watts",\r\n    quote: "The only way to make          sense out of change is to            plunge into it, move with it,        and join the dance."\r\n  },\r\n  etolle: {\r\n    name: "Eckhart Tolle",\r\n    quote: "Realize deeply that the       present moment is all you ever       have."\r\n  },\r\n  tmckenna: {\r\n    name: "Terrence Mckenna",\r\n    quote: "\xe2\x80\x9cThe cost of sanity in        this society, is a certain          level of alienation\xe2\x80\x9d "\r\n  }\r\n};\r\n\r\n$(\'.mybutton\').click(function() {\r\n  var keys = Object.keys(quotes);\r\n  var rand = keys[Math.floor(Math.random() * keys.length)];\r\n  $(\'#quote\').html(quotes[rand].quote);\r\n});
Run Code Online (Sandbox Code Playgroud)\r\n
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>\r\n<button class="mybutton">Quote</button>\r\n<br><br>\r\n<div id="quote"></div>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n