本地存储的 json 数组正在打印,但来自 json 的值在 cordova 应用程序中给出未定义

Locally stored json array is printing but value from json is giving undefined in cordova application

本文关键字:json 应用程序 cordova 未定义 数组 存储 打印      更新时间:2023-09-26

你好,我是JSON的新手,我已经搜索了很多,但没有任何东西对我有用。 我的问题是我正在使用 JSON 中的本地存储保存数据,当我尝试打印数组时它工作正常,但它没有给出值。

这是我在 JSON 中存储数据的代码-

var user;
var users;
   function saveData(){
   if ('localStorage' in window && window['localStorage'] !== null) {
       try {
            user = JSON.stringify({ 
                email : $("#email").val(), 
                timestamp : $("#time").val(),
              }),
           users = localStorage.getItem('user');
           users = users ? JSON.parse(users) : [];
           users.push(user);
           localStorage.setItem("user", JSON.stringify(users)); 
           alert("The data was saved."); 
           return true;
       } catch (e) {
           if (e == QUOTA_EXCEEDED_ERR) {
               alert('Quota exceeded!');
           } 
       }
       } else {
           alert('Cannot store user preferences as your browser do not support local storage');
       } 
    }

我在这里得到这个

  function showData(user_email){
    user_email = {};
   user_email = JSON.parse(localStorage.getItem("user"));
     for(index in user_email){
         alert(user_email[index].email);
     }  
 }

如果我正在打印

alert(user_email[index]);

它工作正常,但是

 alert(user_email[index].email);

这给了我不确定。提前感谢您的帮助。

将用户对象推送到数组之前,不需要将其字符串化。用户数组是对象的数组,而不是字符串。否则,您将在未按预期反对后JSON.parse(localStorage.getItem("user"))为用户返回一个字符串。

它应该只是:

user = { 
    email : $("#email").val(), 
    timestamp : $("#time").val(),
};