lockr.js 本地储存 localStorage操作js库
一个本地储存操作js库,他真的很小,压缩版的甚至<2kb,你可以用类似api的方式来对本地存储进行操作。
1.如何安装lockr
bower install lockr
cnpm i lockr --save你还可以点击在那遥远的地方直接下载使用
<script src="/path/lockr.js" type="text/javascript"></script>
2.API 介绍
Lockr.prefix?- String
?
设置一个字符串用于标记相关的值
Lockr.prefix = 'lockr';
Lockr.set('username', 'Coyote');
localStorage.getItem('username');
localStorage.getItem('lockr_username');
Lockr.set?- :?[ key, value ]?{String, Number, Array or Object}
给本地储存写入值
Lockr.set('username', 'Coyote'); // String
Lockr.set('user_id', 12345); // number
Lockr.set('users', [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]);
Lockr.get?- :?[ key ?/ ?hash_key , 默认值 ]
读取本地储存的值,如果获取到的数值为null/undefined ?则返回设置的默认值
Lockr.get('username');
> "Coyote"
Lockr.get('user_id');
> 12345
Lockr.get('users');
> [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]
Lockr.get('score', 0):
> 0
//不存在返回设置的默认值0
Lockr.set('score', 3):
Lockr.get('score', 0):
> 3
Lockr.rm?- arguments:?[ key ]?{String}
从本地储存中移除相关数据
Lockr.set('username', 'Coyote');
Lockr.get('username');
> "Coyote"
Lockr.rm('username');
Lockr.get('username');
> undefined
Lockr.sadd?- arguments?[ key, value ]{String, Number, Array or Object}
给hash key添加指定值(持续添加类似push 但具备set 自动过滤重复)
Lockr.sadd("wat", 1); // [1]
Lockr.sadd("wat", 2); // [1, 2]
Lockr.sadd("wat", 1); // [1, 2]
Lockr.sismember?- arguments?[ key, value ]
判断某hash key 是否包含某个值 ?返回Boolean true false
Lockr.sadd("wat", 1);
Lockr.sismember("wat", 1); // true
Lockr.sismember("wat", 2); // false
Lockr.smembers?- arguments?[ key ]
返回hash key下的值
Lockr.sadd("wat", 42);
Lockr.sadd("wat", 1337);
Lockr.smembers("wat"); // [42, 1337]
Lockr.srem?- arguments?[ key, value ]
移除hash key下的指定数值
Lockr.sadd("wat", 1);
Lockr.sadd("wat", 2);
Lockr.srem("wat", 1);
Lockr.smembers("wat"); // [2]
Lockr.getAll?- arguments:?null
获取所有数据生成多维数组
Lockr.getAll();获取所有数据生成json数据
> ["Coyote", 12345, [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]]
Lockr.getAll(true);
> [{"username": "Coyote"}, {"user_id": 12345}, {"users": [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]}]
Lockr.flush()?- arguments:?null
清空本地储存所有数据
localStorage.length;
> 3
Lockr.flush();
localStorage.length;
> 0