How to push data to an array on localStorage - Stack Overflow
伊谢尔伦
伊谢尔伦 2017-06-20 10:07:01
0
5
1285

One function I want to do is to set an empty array to localstorage, and push the currently clicked data into the localstorage array every time it is clicked. However, localstorage does not allow push. I have tried deep copying the localstorage array and then pushing it. In the deep copy array, I set the localstorage array to the deep copy array, but I haven’t tried it yet. Please give me some advice

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(5)
世界只因有你

localStorage can only store String, you need to use Json object to convert it:

var arrayObject = [];
arrayObject.push('a','b','c');
localStorage.setItem("array",JSON.stringify(arrayObject));
var arrayObjectLocal = JSON.parse(localStorage.getItem("array"));
arrayObjectLocal.push('d','e','f');
for (i = 0; i < arrayObjectLocal.length; i++) { 
    console.log(arrayObjectLocal[i]);
}
学习ing

It’s very simple. Convert it to json string before saving it, then take it out and reverse it to get a normal array.

localStorage.setItem("arr", JSON.stringify(arr))
var arr = JSON.parse(localStorage.getItem("arr"))
arr.push(something)
localStorage.setItem("arr", JSON.stringify(arr))
我想大声告诉你

Very strange thinking, why not push into the array in localStorage.setItem("arr", arr), but set localStorage first and then perform the operation

ringa_lee

Arrays stored in localstorage will become strings.
If you want to operate the variables of localStorage, you need to take them out first and then store them in.

//设置
arr = [1];
localStorage.arr = arr

Take it out and set it up again

//取出
getarr = localStorage.arr.split(',')
//操作
getarr.push(2)//["1", 2]
//再存
localStorage.arr = getarr//这时候localStorage.arr变为 "1,2"
曾经蜡笔没有小新

Dear, first of all, you need to understand what localstorage is.
localstorage is a permanent storage method in webStorage technology in the new features of HTML5. We usually also call it local storage and cross-session storage.
His usage does not require setting an empty array for localstorage. It has its own method of accessing data, as follows:

localstorage["key"] = 'value' ;

Hope it can help you~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template