-1

我的代码如下:

var employee = {};

employee["fullname"] = document.userForm.fullname.value;
employee["license"] = document.userForm.license.value;
employee["address"] = document.userForm.address.value;
employee["dob"] = document.userForm.dob.value;
employee["city"] = document.userForm.city.value;
employee["state"] = document.userForm.state.value;
employee["zip"] = document.userForm.zip.value;
employee["sex"] = document.userForm.sex.value;

sessionStorage.setItem("session", JSON.stringify({"employees": [employee]}));

以这种方式存储是否正确?此外,如果这是正确的,我如何使用检索信息getItem

4

2 回答 2

1

检索它:

 var mySessionData = sessionStorage.getItem("session");
 var mySessionDataParsed = JSON.parse( mySessionData );

编辑

以这种方式存储是否正确

 //sessionStorage.setItem("session", JSON.stringify({"employees": [employee]}));
 sessionStorage.setItem("session", JSON.stringify( employee ) );
 // this way is suffisant ! 
 // but if you prefer an array you can go with your way too !
于 2015-10-13T18:03:16.933 回答
0

您还可以使用点和/或括号表示法。

sessionStorage["session"] = JSON.stringify({"employees": [employee]});
// or
sessionStorage.session = JSON.stringify({"employees": [employee]});

分配的右侧也是如此。

data = sessionStorage["session"];
// or
data = sessionStorage.session;

无需调用 get 和 set item 方法,因为您只是增加了不必要的开销。

于 2015-10-13T18:08:50.263 回答