admin管理员组

文章数量:1391999

In other languages I have two sets of operators, or and ||, which typecast differently. Does Javascript have a set of operators to pare 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

In other languages I have two sets of operators, or and ||, which typecast differently. Does Javascript have a set of operators to pare 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

Share Improve this question asked Aug 12, 2011 at 15:58 wersimmonwersimmon 2,8693 gold badges23 silver badges35 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

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 pletely 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

本文标签: JavascriptCompare without typecasting to booleanStack Overflow