2017-08-09 113 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); 

我還沒有測試過代碼。希望這會讓你走:-)