在 chrome.storage.local.set 中使用可变键 [英] Using a variable key in chrome.storage.local.set

查看:34
本文介绍了在 chrome.storage.local.set 中使用可变键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 chrome 扩展.我不知道如何使用变量作为 chrome.storage.local.set() 函数的键.我试过了

I am creating a chrome-extension. I don't know how to use a variable as the key to chrome.storage.local.set() function. I have tried

var key = 'myKey';
chrome.storage.local.get(key, function(val) { 
    chrome.storage.local.set({key:val[key]+param1}); //appending  param1
    alert(val[key]);
}

在这里,我试图获取 val[key] 的值并附加一个字符串 param1 并使用相同的密钥将其放回存储中.但我不能这样做.警报框始终显示未定义.

Here i am trying to get the value of val[key] and append a string param1 and place it back to the storage using the same key. But I am not able to do so. the alert box displays undefined all the time.

但是当我尝试不使用变量 key 时,它工作正常.

But when I try without the variable key , it works fine.

chrome.storage.local.get('myKey', function(val) { 
    chrome.storage.local.set({myKey:val['myKey']+param1}); //appending  param1
    alert(val['myKey']);
}

问题是我使用的 chrome.storage.local.set 不仅可以有字符串参数,还可以有对象参数.

The problem is that I am using chrome.storage.local.set can have arguments of not only string but also objects.

推荐答案

我已经解决了这个问题.而不是使用 chrome.storage.local.set({key:val[key]+param1});

I have solved the problem. Instead of using chrome.storage.local.set({key:val[key]+param1});

我已经用一个对象替换了 json 字符串 {key:val[key]+param1}.

I have replaced the json string {key:val[key]+param1} with an object.

var obj = {};       
var key = "myKey";  
obj[key] += param1;   
chrome.storage.local.set(obj);

这里 obj 有值 {"myKey":"the appended value"}

这篇关于在 chrome.storage.local.set 中使用可变键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆