简体   繁体   English

从 javaScript 中的 function 内部添加到全局数组

[英]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.该代码运行良好,除了页面刷新时它会从全局变量中初始化 iWords。

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. localStorage 和 sessionStorage 属性允许在 web 浏览器中保存键/值对。

There are multiple approaches to tackle this.有多种方法可以解决这个问题。 You could store in localStorage, use cookies or store on server side (in some DB).您可以存储在 localStorage 中,使用 cookies 或存储在服务器端(在某些数据库中)。

Here's an example with localStorage:下面是一个使用 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.根据您的用例,存储在服务器端可能是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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