2017-08-09 118 views
4

我创建了一个随机引用机器,它将呈现来自各种哲学家的随机引用。使用jQuery和Math.random()来选择嵌套对象属性

我有一个对象字面与嵌套对象包含哲学家和他们的引号。使用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); 
     }); 
    }); 

回答

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>

+0

谢谢adeneo。这个解决方案对我很好!真的很感激迅速的回应。 – Lewie

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; 

上的click事件用随机数字来选择你的随机报价

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

我还没有测试过代码。希望这会让你走:-)