在javascript中定义变量的快捷方式 [英] shortcut to existentially define variable in javascript
问题描述
为了避免破坏现有的变量,我有这样的代码
window.x = typeof x!=undefined? x:{}
这似乎是一种非常冗长的方式来定义某些东西,但必须避免控制台错误。
我试了一下,而且它似乎工作正常。
window.x = window.x || {}
可以定义这样的变量吗? / code>
甚至在全球范围内...
x = this.x || {}
window.x = window.x || {}
并且定义了 x
有一个falsy值(零,空字符串,null,NaN,未定义,当然是false),那么该值将被一个新的空对象覆盖。如果您认为这是可以接受的,因为您确信 x
将完全未定义或已经定义为对象,那么确定,继续...
To avoid clobbering existing variables, I have code like this
window.x = typeof x != "undefined" ? x : {}
Which seems like a very long winded way to define something, but necessary to avoid console errors.
I tried this out instead, and it seems to work ok. Is it ok to define a variable like this?
window.x=window.x||{}
Or even in the global scope...
x=this.x||{}
If you use this construct:
window.x=window.x||{}
And x
is defined but has a falsy value (zero, the empty string, null, NaN, undefined, and of course false) then that value will be overwritten with a new empty object. If that is acceptable to you because you are confident that x
will either be completely undefined or already defined as an object then sure, go ahead...
这篇关于在javascript中定义变量的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!