Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

"NULL" value is added in array of localStorage

I'm using this code to add values to local storage:

rowSettings[counter] = [value1, value2, value3];
localStorage.setItem("rowSettings", JSON.stringify(rowSettings));

The result in the localStorage is then:

[null,[1,0,0],[1,0,0],[1,0,0],[1,0,0]].

So how come "null" is being added?

In Chome developer tool I get:

"Uncaught TypeError: Cannot read property '0' of null".

This happens when retrieving the objects back:

var row =0;
var retrievedObject = JSON.parse(localStorage.getItem('rowSettings'));
//Start each function
for (var i = 0; i < 3; i++) {
   console.log(retrievedObject[row][i]);
}
row++;
//End each function

Upvotes: 1

Views: 777

Answers (1)

Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

When you built rowSettings, you started (counter) at index 1 instead of 0. So the 0th element is null. Answer found based on Jonathan's comment.

Upvotes: 1

Related Questions