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

时间:2017-08-09 02:54:42

标签: javascript jquery random 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” "
  }
};

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

    $(document).ready(function() {
        $('.mybutton').click(function() {
            $('#quote').html(quotes.awatts.quote);
        });
    });

2 个答案:

答案 0 :(得分:1)

数据的结构似乎很好。您可以使用数组,但对象不是问题。

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

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” "
  }
};

$('.mybutton').click(function() {
  var keys = Object.keys(quotes);
  var rand = keys[Math.floor(Math.random() * keys.length)];
  $('#quote').html(quotes[rand].quote);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybutton">Quote</button>
<br><br>
<div id="quote"></div>

答案 1 :(得分:0)

如果你可以使你的quotes对象成为一个数组,那么下面就可以了。更改阵列

var quotes = [
  {
    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."
  },
  {
    name: "Eckhart Tolle",
    quote: "Realize deeply that the       present moment is all you ever       have."
  },
  {
    name: "Terrence Mckenna",
    quote: "“The cost of sanity in        this society, is a certain          level of alienation” "
  }
];

设置最大值和最小值(设置随机数的上限和下限)

var max = quotes.length, min = 0;

生成随机数

var rand = Math.random() * (max - min) + min;

在点击事件中,使用随机数选择随机引用

$('#quote').html(quotes[rand]quote);

我没有测试过代码。希望这能让你前进: - )