Javascript html5 window.localStorage.getItemItem获取以
我怎么能用它呢Javascript html5 window.localStorage.getItemItem获取以,javascript,html,Javascript,Html,我怎么能用它呢 window.localStorage.getItem() 在localstarage中指定以字符串'QQ'开头的项目。在我的例子中,密钥可以是:QQ+3位,因此我只需要指定它以字符串开头。'QQ'。?如果没有,则获取所有项目并单独检查它们(代码未测试): var结果=[]; 对于(i=0;i
window.localStorage.getItem()代码>
在localstarage中指定以字符串'QQ'
开头的项目。在我的例子中,密钥可以是:QQ+3位,因此我只需要指定它以字符串开头。'QQ'
。?如果没有,则获取所有项目并单独检查它们(代码未测试):
var结果=[];
对于(i=0;i
如果您想进行查询,请使用以下内容
未测试的代码我使用此代码:
var keyIndex = 0;
var thisKey = window.localStorage.key(keyIndex);
while(thisKey != '' && thisKey != undefined)
{
if (thisKey.substr(0, 2) == 'QQ')
{
// do whatever you need to do with thisKey
}
keyIndex+= 1;
thisKey = window.localStorage.key(keyIndex);
}
但robertc的解决方案也是正确的,这样做更简单。实际上,我也修改了代码来执行for循环。遇到了这个问题,下面是es6中的一个解决方案:
let search = 'QQ';
let values = Object.keys(localStorage)
.filter( (key)=> key.startsWith(search) )
.map( (key)=> localStorage[key] );
最好的更新答案,但写出完整的函数,而不是使用箭头函数,然后切换键.startsWith
为键.match(search)
(其中search类似于“^startsWithText”
),以便在IE/旧浏览器中工作。你真是个天才:)
var keyIndex = 0;
var thisKey = window.localStorage.key(keyIndex);
while(thisKey != '' && thisKey != undefined)
{
if (thisKey.substr(0, 2) == 'QQ')
{
// do whatever you need to do with thisKey
}
keyIndex+= 1;
thisKey = window.localStorage.key(keyIndex);
}
let search = 'QQ';
let values = Object.keys(localStorage)
.filter( (key)=> key.startsWith(search) )
.map( (key)=> localStorage[key] );