将索引数组添加到localStorage

时间:2012-12-18 15:53:08

标签: javascript jquery-mobile cordova local-storage

如何将此索引数组names添加到localStorage。并调用此元素:

var name= new Array();

for( var i=0; i<results.rows.length; i++ ) {
    names[results.rows.item(i).IdTypePrestation ] = results.rows.item(i).LibellePrestation;
}

如果我更改此行:

names[results.rows.item(i).IdTypePrestation] = results.rows.item(i).LibellePrestation;

对此:

names[i] = results.rows.item(i).LibellePrestation;

一切都很好,但我需要第一行。

3 个答案:

答案 0 :(得分:0)

设为localStorage

localStorage.someArrayValue = JSON.stringify(myArray);

localStorage获取

myArray = JSON.parse(localStorage.someArrayValue);

答案 1 :(得分:0)

我认为您的解决方案应如下所示:

//Set names on tableau_type line of localStorage
localStorage['tableau_type'] = JSON.stringify(names);

//Get all names on tableau_type line of localStorage
var retrievedObject = JSON.parse(localStorage['tableau_type']);
$.each(retrievedObject ,function(index,element){
    alert(element);
});

答案 2 :(得分:0)

对于存储数组,http://rhaboo.org比对整个事物进行字符串化更有效。后者的问题在于,只要对其进行一些更改,就必须对整个数组进行解码和重新编码,例如添加一个新项目。有了rhaboo,你就写了:

var names = [ ... whatever ... ];
var store = Rhaboo.persistent("Libellen");
if ( store.libellen === undefined ) 
  store.write( 'libellen', names );
for (var i = 0; i < store.libellen.length; i++)
  console.log( JSON.stringify( store.libellen[i] ) )
store.libellen.push("Libelle number " + store.libellen.length);
//Now reload and see it persist.

BTW,我写了rhaboo。