简体   繁体   中英

Adding to global array from inside a function in javaScript

trying to build a quick game. Whereby the word appears at the top of the page, the users click on the correct antonym. I'm trying to add functionality so the users can add their own word pairs. For example:

var iWords = ['new','tall','hot'];
var btn = document.getElementById('btn');

btn.addListenerEvent('click', function() {
var newWord = prompt('What word do you want to add?');
iWords.push(newWord);
});

The code works perfectly, other than when the page refreshes it initalizes iWords from the global var.

Is there any way to permanently push the added words in?

Many thanks, Tom

The localStorage and sessionStorage properties allow to save key/value pairs in a web browser.

There are multiple approaches to tackle this. You could store in localStorage, use cookies or store on server side (in some DB).

Here's an example with localStorage:


// define iWords array & initialize it as empty array.
let iWords = [];

// Check if any existing iWords exists in local storage
const dataInLocalStorage = localStorage.getItem('iWords');
if (dataInLocalStorage !== null) {
    iWords = JSON.parse(dataInLocalStorage);
} else {
  // otherwise initialize iWords with some values.
  iWords = ['new', 'tall', 'hot'];
}


var btn = document.getElementById('btn');

btn.addListenerEvent('click', function () {
  var newWord = prompt('What word do you want to add?');
  iWords.push(newWord);
  // now here, whenever user enters a new word, store & update in localStorage
  // when the page will be refreshed, this stored value will be extracted 
  // from localStorage and assigned to iWords
  localStorage.setItem('iWords', JSON.stringify(iWords));
});


The caveat here is that this is still a temporary storage in browser and won't be stored forever. Storing on server side could be better option, depending on your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM