方法1如下:
方法1的问题:如果刷新浏览器,数据会丢失;
/**
* 自定义map服务
*/
app.service("map", function() {
var data = [];
// 保存map值
this.put = function(key, value) {
for (var i in data) {
// 判断key对应的值是否存在,若存在则修改对应的值
if (data[i]._key == key) {
return data[i]._value = value;
} else {
data.push({_key: key,_value: value});
}
}
};
// 通过key值获取map值
this.get = function(key) {
for (var i in data) {
if (data[i]._key == key) {
return data[i];
}
}
}
// 通过key值删除map对应的值
this.remove = function(key) {
for (var i in data) {
if (data[i]._key == key) {
return data.splice(i, 1);
}
}
}
// 获取全部数据
this.all = function() {
return data;
}
// 清空map全部数据
this.removeAll = function() {
return data.splice(0, data.length);
}
});
方法2:
/**
* 自定义map服务
*/
app.service("map", function() {
// 保存map值
this.put = function(key, value) {
var item = {value: value};
localStorage.setItem(key, JSON.stringify(item));
};
// 通过key值获取map值
this.get = function(key) {
var item = JSON.parse(localStorage.getItem(key));
return item.value;
}
// 通过key值删除map对应的值
this.remove = function(key) {
localStorage.removeItem(key);
}
// 获取存储的长度
this.size = function() {
return localStorage.length;
}
});
欢迎加入,Java,前端的共同学习【爱问共享编程部落】 479668591