문제

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