(变量或 {})可以在 Javascript 中跨浏览器工作吗?
以下构造中的 if(variable)
子句检查列表/数组是否不为 null/未定义,以避免异常:
if (list)
for (var k in list) {
...
if (array)
for (var i = array.length; i >= 0; i--) {
...
但是 JS 语法允许这样的表达式
null || []
undefined || {}
因此我可以将代码缩短一行并且仍然检查数组/对象:
for (var k in obj || {}) {
...
for (var i = (array || {}).length; i >= 0; i--) {
...
问题本质上是:null/undefined || 是否为空? []/{}
表达式在所有浏览器中返回后者?
编辑:发现大括号更适合for (var k in list || {})
迭代,因为数组(方括号)会导致迭代和异常被抛出。
The if(variable)
clause in the following constructs checks if list/array is not null/undefined, to avoid an exception:
if (list)
for (var k in list) {
...
if (array)
for (var i = array.length; i >= 0; i--) {
...
But JS syntax allows expressions like
null || []
undefined || {}
So I can make code shorter by one line and still check the array/object:
for (var k in obj || {}) {
...
for (var i = (array || {}).length; i >= 0; i--) {
...
The question essentially is: does null/undefined || []/{}
expression return the latter in all browsers?
edit: found out that curly brackets are better for for (var k in list || {})
iteration, because an array (square brackets) cause an iteration and an exception is thrown.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,
null
、undefined
、0
、""
都将解析为false
,当被视为布尔值时(||
运算符所做的),因此,所有浏览器都将使用后者。这种行为是完全安全的。Yes,
null
,undefined
,0
,""
, will all resolve tofalse
, when treated as a boolean (which the||
operator does), and so, all browser will use the latter. This behavior is perfectly safe.是的,
我讨厌 15 个字符的限制。
Yes
I hate the 15 char limit.