我看了一些例子,但似乎无法弄明白。基本上我在 ionic 应用程序中有一个联系表,允许用户联系列表所有者。
当他们提交表单时,我想将广告 ID 存储在本地存储中,这样他们就无法重复提交它。
我需要能够存储 json 数组,然后检查结果。如果广告 ID 在 session 存储中,则不显示表单,否则显示它。
我目前正在这样做,它似乎将广告 ID 存储在一个数组中,但我如何循环检查一个 ID 是否存在?我尝试了 angular forEach,但结果是作为一个对象出现的。
// Parse any JSON previously stored in allEntries
var existingEntries = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
if(existingEntries == null) existingEntries = [];
var adId = {
"id":$scope.adId
};
// Save allEntries back to local storage
existingEntries.push(adId);
localStorage.setItem("store_owner_ad_contacts", JSON.stringify(existingEntries));
var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
angular.forEach(values, function(value, key) {
// ^ This is coming as an object how can I get the key value?
if(value == adId){
//form has been submitted before
}else{
// showformVar = true
console.log(key + ': ' + value);
});
我的存储是这样的
[{"id":"100033"},{"id":"100035"},{"id":"1000336"}]
如何获取id值? (例如 1000033)
最佳答案
在你的循环中你有一个对象,所以像访问对象一样访问 id 属性:object.yourProperty 或 object[yourProperty]
var values = JSON.parse(localStorage.getItem("store_owner_ad_contacts"));
values.forEach(values, function(item, i) {
// you get object like this {id: "100033"}
// so to access id do like normal object
if (item.id === '100033') {
// do something
}
});
关于javascript - localStorage 使用 Angular 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38581398/