سؤال

Possible Duplicate:
null coalescing operator for javascript?

In C#, you can do this:

var obj = newObject ?? defaultObject;

That says assign newObject to obj if not null else assign defaultObject. How do I write this in javascript?

هل كانت مفيدة؟

المحلول

While it's considered an abusage, you can do the following:

var obj = newObject || defaultObject;

Note that if newObject is of any falsy value (such as 0 or an empty string), defaultObject will be returned as the value of obj. With this in mind, it may be preferred to use either the ternary operator or a standard if-statement.

var obj = ( "undefined" === typeof defaultObject ) ? defaultObject : newObject ;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top