[英]JSON.parse fallback for undefined array to avoid exception
I'm parsing my array and everything is OK if it is defined: 我正在解析我的数组,如果已定义,则一切正常:
JSON.parse(myArray);
However I get an exception in case if myArray is undefined. 但是,如果myArray未定义,我会遇到异常。
What is the best fallback for it, is there anything better than this: 最好的后备方法是什么呢?
JSON.parse(myArray || '[]');
similar like we first verify the object to avoid an exception if undefined 类似于我们首先验证对象以避免未定义的异常
if (obj) {
//do something with obj.something
}
So, is there anything shorter than 所以,有没有什么比
JSON.parse(myArray || '[]');
Thank you. 谢谢。
Your current method works just fine as well. 您当前的方法也很好。 I don't really see a reason to change it but if you feel you need to two options come to mind:
我看不出有更改它的理由,但是如果您觉得需要两个选择,请考虑:
First, you could initialize myArray
with it defaulted to an empty array before it gets its values assigned. 首先,可以在初始化
myArray
之前将其默认为一个空数组,然后再为其分配值。
var myArray = '[]';
Otherwise if myArray
is a parameter passed to a method you are parsing it from, you can default it in the arguments section. 否则,如果
myArray
是传递给要从中进行解析的方法的参数,则可以在arguments部分中将其默认设置。
function dosomething(myArray = '[]') {
JSON.parse(myArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.