开发者

Will (variable or {}) work crossbrowser in Javascript?

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 th开发者_开发问答e 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.


Yes, null, undefined, 0, "", will all resolve to false, when treated as a boolean (which the || operator does), and so, all browser will use the latter. This behavior is perfectly safe.


Yes

I hate the 15 char limit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜