gpt4 book ai didi

javascript - 使用 ngStorage/localstorage 保存键=>值样式

转载 作者:行者123 更新时间:2023-11-30 00:00:52 25 4
gpt4 key购买 nike

在我的 Ionic 应用程序中,我添加了插件“ngStorage”,它附带了一些演示代码:

var add = function (thing) {
$localStorage.things.push(thing);
}

这完全按照说明工作。我 add("foo") 它,然后执行 getAll() 并且值就在那里。我删除了 add(),但保留了 getAll(),我仍然有值“foo”(正如预期的那样)。

这对我来说不是很有用,我想用 key 访问它,所以我做了以下内容:

var addByKey = function (key, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}

当我执行 addByKey("foo","bar") 然后执行 getAll() 时,我得到了我想要的值。当我删除 addByKey() 并重新加载时,我希望它仍然记得设置信息,但它不存在。然而,通过 add() 函数的第一次尝试仍然存在,“foo”仍然存在(意味着数组没有重置)。

如何制作键->值类型的结构?


如果它有用:

.factory ('StorageService', function ($localStorage) {
$localStorage = $localStorage.$default({
things: []
});
var _getAll = function () {
return $localStorage.things;
};

var _add = function (thing) {
$localStorage.things.push(thing);
}
var _addByKey = function (thing, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}

return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})

最佳答案

假设你想要一个键值存储系统,你可以简单地使用一个对象而不是一个数组,这样每个键都可以设置为这个对象的一个​​属性。

.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {}
});

var _getAll = function() {
return $localStorage.things;
};
var _addByKey = function(thing, value) {
$localStorage.things[thing] = value;
}

return {
getAll: _getAll,
addByKey: _addByKey
};
})

但是,假设您想在主集合上保留所有值的引用并通过键访问它们,您可以考虑使用对象来存储数组的事物。这样您就可以使用一个属性来存储所有项目(您也可以存储在不同的地方),并通过引用集合中所需的值来使用此对象来存储您的键。

You may need to implement the deletion logic to maintain the consistence between the collection and the dictionary.

你的工厂看起来像这样:

.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {
items: []
}
});

var _getAll = function() {
return $localStorage.things.items;
};

var _add = function(thing) {
$localStorage.things.items.push(thing);
}
var _addByKey = function(thing, value) {

var i = $localStorage.things.items.push(value) - 1;
$localStorage.things[thing] = $localStorage.things.items[i];
}

return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})

关于javascript - 使用 ngStorage/localstorage 保存键=>值样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40587243/

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