localStorage中空数组的JSON.parse结果问题

3

我使用以下函数初始化了一个localStorage变量:

    if (!localStorage["store"]) {
       var aaa = new Array();
       localStorage["store"] = JSON.stringify(aaa);
    }   

看起来它工作得很好,但当我尝试使用该数组来添加元素时,使用以下代码:

  var one_stat = new Array( s1, s2 , resultat );
  var statistics = JSON.parse(localStorage["store"]);
  statistics.push( one_stat );
  localStorage["store"] = JSON.stringify(statistics);

我遇到了以下错误:
未捕获的类型错误:对象[]没有 push 方法
我在 Ubuntu 上使用 Google Chrome 10.0.648.151。
有人知道我可能做错了什么吗?
谢谢。

可能是重贴 https://dev59.com/XG435IYBdhLWcg3w20B8 - Lance
console.log(localStorage.store); 我的猜测是你将localStorage.store初始化为除数组之外的其他内容,现在它已被设置,但由于if语句的判断结果为false,所以你的代码没有将其重置为空数组。 - JaredMcAteer
alert(localStorage["store"]) 的输出是什么?另外,如果您只是遇到空数组的问题,您尝试过简单地使用 localStorage["store"] = "[]" 吗? - Aleadam
无论他在localStorage数组中有什么...他试图将文本放入对象中,并使用数组push方法向JSON对象添加其他数据。对象没有push方法。它会失败,无疑。 - Lance
console.log(localStorage["store"]) 的输出是 "[]" - Carles Andres
当然是这样的... 你没有将任何东西存储在localStorage["store"]中。 - Lance
2个回答

2

我尝试了以下代码,结果如预期:

<!DOCTYPE html>         
<html>                  
<head>
<title>Prova</title>    
</head>                 
<body>
<script type="text/javascript"> 
        if (!localStorage["stor"] ) {

                localStorage["stor"] = JSON.stringify([]);
        }               

        var aa = JSON.parse( localStorage["stor"] ) ;
        console.log( aa ) ;
        aa.push( [ 1 , 2, 2 ] ) ;
        localStorage["stor"] = JSON.stringify( aa ) ;
</script>
I am trying, man
</body>
</html> 

看起来这与我正在使用的Prototype库有关。看看这个:JSON.stringify() array bizarreness with Prototype.js

我还没有找到解决方案,但我相信我正在走在正确的道路上。


解决了。这是与Prototype 1.6.x已知的冲突。我更新到了Prototype 1.7,问题得到了解决。更多信息请参见:[https://prototype.lighthouseapp.com/projects/8886/tickets/730-prototypejs-breaks-firefox-35-native-json]。感谢@Lance @Aleadam和@OriginalSyn的帮助。 - Carles Andres

0

本质上,JSON对象不是数组,而且在JavaScript中push方法只适用于数组。您为什么不使用对象字面量方法将数组数据添加到JSON对象中呢?

例如:

statistics.variable = one_stat;

1
抱歉,我不明白。我不能直接将任何东西(例如数组)保存到localStorage [“store”]中吗?我的意思是,JSON.parse难道不应该返回我的空数组吗? - Carles Andres
JavaScript数组和对象有不同的方法。你正在使用的一个方法——'push'——不能与你的JSON对象一起使用,因为对象没有push方法。相比之下,数组确实有一个push方法。 JSON.parse返回一个JSON对象,而不是一个数组。http://www.json.org/js.html可以在那里找到更多信息。你到底想要实现什么?看起来你想把统计数据保存到localStorage['store']中的一个数组中。如果你只想要一个数组存储容器,为什么还要使用JSON.parse呢? - Lance
Lance,感谢你的所有回答,但它们并没有解决我的问题。我需要知道如何将一个数组存储到localStorage中,以便稍后可以使用'push'。我知道我可以使用对象,但我确信一定有一种方法可以将空数组或整个n维数组存储到localStorage中,并将其检索回来,就像之前一样。我会非常感激任何帮助。 - Carles Andres

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接