我正在创建一个随机引用机器,它将呈现各种哲学家的随机引用.
我有一个包含哲学家及其引号的嵌套对象的对象文字.使用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);
});
});
最佳答案 数据的结构似乎很好.您可以使用数组,但对象不是问题.
你从对象中获取密钥,然后选择一个随机密钥
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>