最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - Compare without typecasting to boolean - Stack Overflow

programmeradmin2浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论