如何隐藏数组中未定义的变量
在继续阅读之前仅供参考...我不是那种每次找不到问题解决方案就跑到 stackoverflow 的人,但这确实让我头晕目眩。
如何在数组中隐藏未定义的变量:
var state_zip = address.split(',')[2];
我希望变量 state_zip 在输出数据时输出为空白“”而不是“未定义”。
这些似乎对我也不起作用。
ar more2 = address.split(',')[4];if (more2.split(',')[4]=="undefined"){more2=""}
ar more2 = address.split(',')[4];if (more2.split(' ')=="undefined"){more2=""}
任何可以帮助我理解这一点的人将不胜感激。我更多的是后端开发人员,所以这有点不符合我的正常环境。
Just an FYI before you continue reading...I'm not the type to run to stackoverflow every time I can't figure out a solution to my problem but this one has really got my head spinning.
How do I hide an undefined variable inside of an array:
var state_zip = address.split(',')[2];
I want the variable state_zip to output as blank "" instead of "undefined" when outputting data.
These didn't seem to work for me either.
ar more2 = address.split(',')[4];if (more2.split(',')[4]=="undefined"){more2=""}
ar more2 = address.split(',')[4];if (more2.split(' ')=="undefined"){more2=""}
Anyone who can help me understand this would be greatly appreciated. I'm more of a backend developer so this is a little bit out of my normal environment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
尝试使用 typeof:
Try using typeof:
undefined 不是一个 javascript 关键字吗?您应该能够做到
无需报价。
Isn't undefined a javascript keyword? You should be able to do
No need for quotes.
检查数组长度:
当你尝试读取超出其范围的 JS 数组时,你会得到未定义的结果 - 所以只需确保你在范围内,否则分配空字符串。
您可以通过一次这样的函数来使其更加通用:
然后像这样调用它:
Check the array length:
When you try to read JS array beyond its bounds, you get undefined - so just make sure you're within the bounds otherwise assign empty string.
You can make it more generic by having such function once:
Then call it like:
不要在
undefined
两边使用引号。您应该通过以下方式检查undefined
-当您在
undefined
周围使用引号时,您基本上是在检查该变量是否包含字符串"undefined"
。jsfiddle 上的示例
Don't use quotes around
undefined
. You should be checking forundefined
in the following way -When you use quotes around
undefined
, you are basically checking whether or not that variable contains the string"undefined"
.An example on jsfiddle
我认为使用 jquery 你可以这样做:
var more2 = address.split(',');
$.each( more2, 函数(i, l){
I think using jquery you can do something like:
var more2 = address.split(',');
$.each( more2, function(i, l){
如果绳子太短,可以垫一下;
You could pad the string if it's too short;