[英]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.