![](/img/trans.png)
[英]Object is possibly null error (typescript) when trying to display the value of an array which is stored in localstorage
[英]Array is null when trying to use .push after localstorage
当我尝试将新值推入数组时,我收到一个TypeError说我的数组为null。
//first off..
var sillyArray= ["dummy"];
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
//I later used this
sillyArray = JSON.parse(localStorage.getItem("sillyArray"));
//the error is here
sillyArray.push("yes");
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
我无法推送或解析吗?
(编辑过帐错误)
yesArray
从未definded
。 这就是为什么.push()
是不可能的。
是的,可以,但是您正在尝试将项目推入undefined
var中,这就是为什么会收到TypeError的原因 。
这是您应该执行的操作:
var array = ['dummy'];
localStorage.setItem('someKey', JSON.stringify(array));
array = JSON.parse(localStorage.getItem('someKey'));
array.push('foo');
localStorage.setItem('someKey', JSON.stringify(array));
那如果你做
console.log(JSON.parse(localStorage.getItem('someKey')))
输出将是您期望的结果["dummy", "foo"]
正如用户nnnnnn所说,我没有正确执行我的localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
它坐在一个if语句( 未显示 )中,该语句未执行,导致null。
多谢你们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.