我目前正在制作一个 Chrome 扩展程序,目前正处于最后阶段,即存储用户首选项。
我知道本地存储将存储字符串,在这个阶段,我对仅使用字符串感到困惑,但随着存储需求变得更大,需要一个二维数组。我已经看到本地存储无法存储数组,但您可以使用 JSON。我从未使用过 JSON,在查看示例时,我不明白该怎么做。
for (i=1;i<=localStorage["totalwebsites"];i++) {
// Get the title of the current item
var title = localStorage["websitetitle" + i];
// Create the new context menu item, and get its menuItemId to store in the right localStorage string
var menuItemId = chrome.contextMenus.create({parentId: ParentID, title: title, contexts:["selection"], onclick: searchFromContext});
// Store the created menu items menuItemId in the array so we know which item was chosen later on
websitesarray[menuItemId] = localStorage["websiteurl" + i];
}
正如您所看到的,当使用字符串时,这会变得非常困惑、非常快。我希望totalwebsites成为数组中项目的计数,而websitetitle和websiteurl成为二维数组。
我不知道如何在 JSON 中执行此操作,或者至少不知道如何将其永久存储在 Chrome 本身中。我猜你必须在某个时候将其转换回本地存储字符串?我不认为我明白这一点。
任何帮助/指示将不胜感激,我找不到太多:(
最佳答案
别担心,JSON 非常简单!假设您的网站存储在 websitesarray
中:
// To load:
websitesarray = JSON.parse(localstorage.websites);
// To store:
localstorage.websites = JSON.stringify(websitesarray);
确保您有一个合理的方法来处理尚未设置 localstorage.websites
的情况,因为如果输入为 JSON.parse
将会抛出异常空。
关于javascript - 在 Chrome 扩展中存储数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8565379/