简体   繁体   中英

When stored data in localstorage first time it will be stored but second time I try to store then it display error push is not function why?

Html code

<body>
    <input type="text" id="userName">
    <button onclick="empShow()">Click</button>
</body>
<script src="script.js"></script>

Javascript Code

function empShow(){
    let emp=[];
    let name=document.getElementById('userName').value;
    let data={UserName:name};
     emp=JSON.parse(localStorage.getItem('empData')) || [];
    emp.push(data); //when i try to push data second time it display emp.push is not function.
    localStorage.setItem('empData',JSON.stringify(data));
}

When I change localstroge key then it is stored but when run the second time it will display error.

While inserting the data for the fist time in localStorage:

localStorage.getItem('empData')

was null . Now at that (first) time,

null || [] 

resulted into [] . ie an array.

Then in the next line you called push method on an array. It worked. The 2nd time however,

localStorage.getItem('empData')

was not null. Let's consider the first time you entered "Test" in the text box. So the value of localStorage.getItem('empData') becomes '{"UserName":"test"}'.

The string value parsed into a JSON object transformed variable emp a JSON variable. A JSON value ORed with the empty array [] resulted into the JSON itself this time, which is not an array and does not have a push method either. As a result you are getting that error.

While storing the data always setItem
By using JSON.stringify();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM