javascript - 如何将值推送到本地存储?

标签 javascript php arrays json local-storage

我在js中有以下代码。如果我使用静态数组,一切正常。否则我得到:

Uncaught TypeError: myArray.push is not a function

function test(){
var myArray =  localStorage.getItem('articles')  ;
//myArray=[1,4,5];
needle = 2    ,
myArray.push(needle);
localStorage.setItem('articles', JSON.stringify(myArray))
console.log(localStorage.getItem('articles'));
}

最佳答案

由于要对其进行字符串化,因此需要将其解析为字符串格式才能使用 push:

var myArray = JSON.parse(localStorage.getItem("articles"));

关于javascript - 如何将值推送到本地存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56334415/

相关文章:

javascript - react : Update className of this. props.children

javascript - jquery ui可排序修改创建时的html

PHP json_encode 作为 PHP 数组 unset() 后的对象

python - Numpy.where 函数没有在数组中找到值......有人知道为什么吗?

ruby - 如果指定键的值在数组中相同,如何合并哈希

javascript - HTML5相机缓冲和延迟(延迟镜像)

php - Javascript 在从 ajax 调用获取结果之前执行

php - 多次上传到MySql数据库,foreach不提交照片

php - 给定一个数组数组,如何从每个值中去除子字符串 "GB"?

javascript - 如何在 <div> 后面的 <div> 上锁定滚动