Javascript Random Value in Local Storage?

Hi, I have a small code that returns a random key from the local storage. Now I want to modify the code so that it returns a random value.

Can anyone help me?

 function nextVocabulary(){    let obj_keys = Object.keys(edictionary);    randomGermanWord = obj_keys[Math.floor(Math.random() * obj_keys.length)];    word.innerHTML = `${edictionary[randomGermanWord]}?`; }
(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
2 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
regex9
1 year ago

The keys-Method provides you with an array of all keys (or property names) valuesMethod an array of all values. Consequently, you only need a randomly generated index to get a value from the respective array.

const vocabularies = {
  "Baum": "tree",
  "Himmel": "sky",
  "Sonne": "sun"
};

function getRandomGermanVocabulary() {
  return getRandomElement(Object.keys(vocabularies));
}

function getRandomEnglishVocabulary() {
  return getRandomElement(Object.values(vocabularies));
}

function getRandomElement(data) {
  const index = Math.floor(Math.random() * data.length);
  return data[index];
}

The solution from your question text works as well.

On the other hand, the approach is not correct, since the indexer can only resolve keys to values. It is searched for a property with the name of the key. Access via

vocabularies["Baum"]

therefore provides the value tree but in this attempt to access:

vocabularies["tree"]

you get the value undefinedbecause the object does not name a property tree has.

PS.: As long as you only insert Plaintext into the DOM, there is no need to interpret HTML. That is, it is completely enough that textContent– Use property. It’s more resource-saving.

word.textContent = "Some text ...";