javascript 如何从localStorage中检索JSON数据,如单独的电子邮件名称

iezvtpos  于 2023-02-18  发布在  Java
关注(0)|答案(2)|浏览(107)
var testObject = { 'name': 1, 'email': 2, 'password': 3 };

 // Put the object into storage
 localStorage.setItem('testObject', JSON.stringify(testObject));

 // Retrieve the object from storage
 var retrievedObject = localStorage.getItem('testObject');

 console.log('retrievedObject: ', JSON.parse(retrievedObject));

我只想显示电子邮件或姓名怎么办

fdx2calv

fdx2calv1#

你可以这样做

const testObject = { 'name': 1, 'email': 2, 'password': 3 };

// Put the object into storage 
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage 
const retrievedObject = localStorage.getItem('testObject');

//JSON.parse first
const myObj = JSON.parse(retrievedObject);
//Then access each key value separate
console.log('name: ', myObj.name);//outputs: 1
console.log('email: ', myObj.email);//outputs: 2
sdnqo3pr

sdnqo3pr2#

const retrievedObject = JSON.parse(localStorage.getItem('testObject'));

然后您访问名称和电子邮件,如下所示:

const name = retrievedObject.name
const email = retrievedObject.email

相关问题