Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I was able to get it to work with Mash's algorithm (I made two minor fixes to it, and updated that answer with them.) You're right about the <code>JSON.parse</code> being unnecessary with jQuery's <code>getJSON</code>. It's <strong><a href="http://jsbin.com/itaxif/2" rel="nofollow">running on JSBin</a></strong>:</p> <pre><code>var words = (function() { var wordList, numWords; return { load: function(data) { wordList = data; numWords = 0; for (var x in wordList) { numWords += wordList[x].length; } words.random = function() { var wordIndex = Math.floor(Math.random() * numWords); console.log(wordIndex); for (var x in wordList) { if (wordIndex &gt;= wordList[x].length) { wordIndex -= wordList[x].length; } else { return wordList[x][wordIndex]; } } }; }, random: function() { return undefined; // or throw exception? // not initialized yet } }; }()); var print = (function() { var $console = $("#console"); return function(msg) { $console.text($console.text() + "\n" + msg); }; }()); $("#random").click(function() { print("Random word: " + words.random()); }); print("Random word before load: " + words.random()); $.getJSON("http://jsbin.com/ukaxec/2/js") .then(words.load) .then(function() {print("Random word after load: " + words.random());}); </code></pre> <p>The <code>$.getJSON()</code> call is just calling a small list of words, a minimal extension of your example, also hosted on JSBin.</p> <p>Note that before the JSON is successfully loaded, the function <code>words.random</code> is just a dummy function, which gets overridden once the words are in place.</p> <p>But I still wonder, if you're only going to use this to load a single word, why you would bother to send the whole list down to the client.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload