Javascript chrome.storage.local.set 使用可变键名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11692699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
chrome.storage.local.set using a variable key name
提问by user1558225
In a Google Chrome Extension, I want to use chrome.storage.local
(as opposed to localStorage) because:
在 Google Chrome 扩展中,我想使用chrome.storage.local
(而不是 localStorage),因为:
- With key-value pairs, the value can be any object (as opposed to string only)
- Changes to the data model using setter
storage.set
can trigger an event listener
- 使用键值对,值可以是任何对象(而不是仅字符串)
- 使用 setter 更改数据模型
storage.set
可以触发事件侦听器
Using storage.set
, how can I have a variable key name?
使用storage.set
,我怎么能有一个可变的键名?
Note: If I don't use the setter, I can do storage[v1]
, but changes to the object won't trigger the event listener.
注意:如果我不使用 setter,我可以这样做storage[v1]
,但是对对象的更改不会触发事件侦听器。
var storage = chrome.storage.local;
var v1 = 'k1';
storage.set({v1:'s1'});
storage.get(v1,function(result){
console.log(v1,result);
//console output = k1 {}
});
storage.get('v1',function(result){
console.log(result);
//console output = {v1:'s1'}
});
回答by PAEz
Is this what you where looking for?
这是你要找的吗?
var storage = chrome.storage.local;
var v1 = 'k1';
var obj= {};
obj[v1] = 's1';
storage.set(obj);
storage.get(v1,function(result){
console.log(v1,result);
//console output = k1 {v1:'s1'}
});
storage.get('v1',function(result){
console.log(result);
//console output = {v1:'s1'}
})
回答by Xan
It's 2016, and Chrome (and Firefox, and Edge - everyone using Chrome extension model) support ES6 Computed Property Names.
现在是 2016 年,Chrome(以及 Firefox 和 Edge——每个人都使用 Chrome 扩展模型)支持 ES6 Computed Property Names。
With that, the task becomes simpler:
这样,任务就变得简单了:
var storage = chrome.storage.local;
var v1 = 'k1';
storage.set({
[v1]: 's1' // Will evaluate v1 as property name
});
storage.get(v1, function(result) {
console.log(v1, result);
});