繁体   English   中英

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

[英]Adding to global array from inside a function in javaScript

试图建立一个快速的游戏。 当单词出现在页面顶部时,用户点击正确的反义词。 我正在尝试添加功能,以便用户可以添加自己的单词对。 例如:

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

该代码运行良好,除了页面刷新时它会从全局变量中初始化 iWords。

有什么办法可以永久将添加的单词推入?

非常感谢,汤姆

localStorage 和 sessionStorage 属性允许在 web 浏览器中保存键/值对。

有多种方法可以解决这个问题。 您可以存储在 localStorage 中,使用 cookies 或存储在服务器端(在某些数据库中)。

下面是一个使用 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));
});


这里需要注意的是,这仍然是浏览器中的临时存储,不会永远存储。 根据您的用例,存储在服务器端可能是更好的选择。

暂无
暂无

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

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