我在localStorage中存储了一些变量,例如
键:ts_co_1,值:注释11
键:ts_co_2,值:注释22
键:ts_ta_1,值:注释1
键:ts_ta_2,值:注释2
localStorage的长度可以变化。对于每个任务 ts_ta_i ,都有相应的注释 ts_co_i
下面的代码遍历本地存储以获取所有值。我现在想要的是将它们以tupples或list的形式进行排序,以便可以在表中输入这些值。即打印出相应的任务及其注释
(ts_ta_1,ts_co_1) (ts_ta_2,ts_co_2) (ts_ta_3,ts_co_3)
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
console.log('Key: ' + key + ', Value: ' + value);
答案 0 :(得分:2)
您可以执行以下操作:
localStorage
忽略第一部分(这是因为此处不能使用实际的// IGNORE THIS PART (fake localStorage)
class LocalStorageMock {
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value.toString();
}
};
const _localStorage = new LocalStorageMock;
// Save data to fake local storage for the demo
_localStorage.setItem('ts_co_1', 'comment 11');
_localStorage.setItem('ts_ta_1', 'comment 1');
_localStorage.setItem('ts_co_2', 'comment 22');
_localStorage.setItem('ts_ta_2', 'comment 2');
// Actual code starts here (_localStorage is localStorage in real code)
let i = 0, ta, co;
const tuples = [];
while ((ta = _localStorage.getItem('ts_ta_' + ++i)) && (co = _localStorage.getItem('ts_co_' + i))) {
tuples.push(`(${ta}, ${co})`);
}
console.log(tuples.join(' '));
)
{{1}}