开发者

Javascript - Compare without typecasting to boolean

In other languages I have two sets of operators, or and ||, which typecast differently. Does Javascript have a s开发者_高级运维et of operators to compare and return the original object, rather than a boolean value?

I want to be able to return whichever value is defined, with a single statement like var foo = bar.name or bar.title


There is only one set of boolean operators (||, &&) and they already do that.

var bar = {
    name: "",
    title: "foo"
};

var foo = bar.name || bar.title;

alert(foo); // alerts 'title'

Of course you have to keep in mind which values evaluate to false.


var foo = (bar.name != undefined) ? bar.name : 
          ((bar.title != undefined) ? bar.title : 'error');


var foo = bar.name || bar.title;

It returns the first defined object.

If none of both is defined, undefined is returned.


I either completely missunderstood the question or it's just straighforward like you mentioned:

var foo = bar.name || bar.title;

if bar.name contains any truthy value it's assigned into foo, otherwise bar.title is assigned.

for instance:

var bar = {
    name: null,
    title: 'Foobar'
};

var foo = bar.name || bar.title
console.log( foo ); // 'Foobar'


Javascript behaves exactly like you want:

var a = [1, 2],
    b = [3, 4];

console.log(a || b); //will output [1, 2]
a = 0;
console.log(a || b); //will outout [3, 4]

If you whant to typecast to boolean you can use double negative operator:

console.log(!![1, 2]); //will output true
console.log(!!0); //will output false
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜