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
5 Answers
Reset to default 6There 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
版权声明:本文标题:Javascript - Compare without typecasting to boolean - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744594624a2614699.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论