Using jQuery and Math.random () to select properties of nested objects

I create a random quote machine that will present a random quote from various philosophers.

I have an object literal with nested objects containing philosophers and their quotes. Using jQuery and Math.random () functions, how can I select a random quote from my object literal structure? Is there a better way to organize the data?

I started by closing jQuery, which will display the assigned quote, which I would like to change using Math.random ().

Looking for an explanation of the solutions as I am new. Thanks in advance.

Example object literal:

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

Examples of jQuery functions with a single quotation mark selected:

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

. , .

,

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>
Hide result
+1

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

max min ( )

var max = quotes.length, min = 0;

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

,

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

. , : -)

0

Source: https://habr.com/ru/post/1683298/


All Articles