我想知道是否有人知道如何从本地存储中调用特定密钥,如下所示:
钥匙清单:
_#12345
_this is a random key
_random123
_#54321
理想的剧本:
MyScript {
Find all keys that start with "_#" then print value of key (ignore other keys)
}
答案 0 :(得分:3)
这应该有效:
// sample values:
localStorage.setItem("_#12345",'Correct');
localStorage.setItem("_this is a random key",'Wrong');
localStorage.setItem("_random123",'Wrong');
localStorage.setItem("_#54321",'Correct');
// iterate over all keys in localStorage
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i); // get key by index
if (key.indexOf("_#") === 0) { // if starts with _#
var elem = localStorage.getItem(key); // get value by key
console.log(elem); // print it out / do something else
}
}
输出:
"Correct"
"Correct"
答案 1 :(得分:0)
调用此函数以打印localstorage值
function PrintLocalstorageValues()
{
for (var i = 0; i < localStorage.length; i++) {
var keyName = localStorage.key(i);
if (keyName.indexOf("_#") ==0) {
var value= localStorage.getItem(keyName);
alert(value); //output ,you can push these into array
}
}
}
感谢