gpt4 book ai didi

javascript - 查询本地存储条目而不抛出错误

转载 作者:行者123 更新时间:2023-12-02 14:24:05 26 4
gpt4 key购买 nike

正在开发 Chrome 扩展。我正在使用以下命令将一些数据保存到本地存储:

chrome.storage.local.set({ [variablyNamedEntry]: someObjectToBeSaved });

在我的代码中的其他地方,我想查询该条目是否存在,如果存在,我将希望使用该对象本地化一些变量“myVar”。

如果该条目存在,则此代码可以实现我的目标:

chrome.storage.local.get(null, function(result){
myVar = result[variablyNamedEntry];
}

但是如果“variableNamedEntry”不存在条目,则会抛出错误。我可以通过 try/catch 序列来管理此错误。但这并不是最好的方法,因为我知道它在很大一部分时间里找不到该条目。

我怎样才能实现我的目标?

更新:

我尝试使用:

chrome.storage.local.get([variablyNamedEntry], function(result){
if (result != undefined)
myVar = result[variablyNamedEntry];
}

但是如果该条目不存在,我仍然会收到以下错误:

 extensions::uncaught_exception_handler:8 Error in response to storage.get: TypeError: Cannot read property 'someProperty' of undefined

最佳答案

请注意the items parameter for the callback of chrome.storage.local.get is always an object并且永远不会未定义

假设您有一个键值,其中键为'Sample-Key',您可以使用以下代码

chrome.storage.local.get(null, function(result){
if(typeof result['Sample-Key'] !== 'undefined') {
console.log(result['Sample-Key']);
}
});

或者

chrome.storage.local.get('Sample-Key', function(result){
if(typeof result['Sample-Key'] !== 'undefined') {
console.log(result['Sample-Key']);
}
});

关于javascript - 查询本地存储条目而不抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com