chrome.storage.local奇怪的行为:被重复的对象困惑 [英] chrome.storage.local strange behaviour: confused by a duplicate object
问题描述
dup =经过很多寻找bug后,我设法缩小了我的问题的范围, {a:[1]}
chrome.storage.local.set({x:[dup,dup]});
chrome.storage.local.get([x],function(o){console.log(JSON.stringify(o ['x']));});
打印出来: [{a:[1]}, null]
我发现这是一个非常奇怪的行为。所以我的问题是:
-
这是故意的吗?它是否有文件记录?
-
你能否推荐一个很好的解决方案来绕过这个限制?
我目前的想法是使用JSON.stringify(正确处理这种情况)并稍后解析字符串。但这样看起来很浪费。
谢谢。
b $ b
- 不,它不是故意的,应该报告为错误: https://crbug.com/606955 (现在它已经修复为Chrome 52!)。 li>
-
正如我在错误报告中解释的,错误的原因是对象是相同的。如果你的对象
dup
只包含简单值(即没有嵌套数组或对象,只有原始值,如字符串,数字,布尔值,null,...),那么浅该对象的克隆就足够了:
$ bdup = {a:[1]}
dup2 = Object.assign({},dup);
chrome.storage.local.set({x:[dup,dup2]});
如果您需要支持嵌套对象,则必须进行深度克隆。有很多现有的库或代码片断,所以我不会在这里重复。准备
chrome.storage
将其序列化为JSON,然后再解析它(然后所有对象都是唯一的)。
dup = {a:[1]}
var valueToSave = JSON.parse(JSON.stringify([dup,dup]));
chrome.storage.local.set({x:valueToSave});
//或者:
var valueToSave = [dup,JSON.parse(JSON.stringify(dup))];
chrome.storage.local.set({x:valueToSave});
After a lot of bug-hunting, I managed to narrow my problem down to this bit of code:
dup = {a: [1]}
chrome.storage.local.set({x: [dup, dup]});
chrome.storage.local.get(["x"], function(o) {console.log(JSON.stringify(o['x']));});
This prints out: [{"a":[1]},null]
Which I find to be a pretty strange behaviour. So my questions are:
Is this intentional? Is it documented?
Can you recommend a good solution to bypass this limitation?
My current idea is to use JSON.stringify (which handles this case correctly) and later parse the string. But that just seems wasteful.
Thanks.
- No it is not intentional and should be reported as a bug: https://crbug.com/606955 (and now it is fixed as of Chrome 52!).
As I explained in the bug report, the cause of the bug is that the objects are identical. If your object
dup
only contains simple values (i.e. no nested arrays or objects, only primitive values such as strings, numbers, booleans, null, ...), then a shallow clone of the object is sufficient:dup = {a: [1]} dup2 = Object.assign({}, dup); chrome.storage.local.set({x: [dup, dup2]});
If you need support for nested objects, then you have to make a deep clone. There are many existing libraries or code snippets for that, so I won't repeat it here. A simple way to prepare values for
chrome.storage
is by serializing it to JSON and then parsing it again (then all objects are unique).dup = {a: [1]} var valueToSave = JSON.parse(JSON.stringify([dup, dup])); chrome.storage.local.set({x: valueToSave}); // Or: var valueToSave = [ dup, JSON.parse(JSON.stringify(dup)) ]; chrome.storage.local.set({x: valueToSave});
这篇关于chrome.storage.local奇怪的行为:被重复的对象困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!