Let f
and g
be two function. Then f() || g()
first evaluates f
. If the return value of f
is falsy it then evaluates g
, and returns g
's return value.
I love the neat and concise syntax, but it doesn't include the case where f
returns the empty array []
, which I want to开发者_运维问答 consider "falsy".
Is there clean way of having this syntax for []
instead of the traditional falsy values?
You could write a function that converts the empty array into a real falsy value, maybe?
function e(a) { return a instanceof Array ? (a.length ? a : false) : a; }
var result = e(f()) || g();
The problem with the other solutions presented is that it doesn't behave exactly how you may want the short-circuiting to work. For example, converting the value of f()
to a truthy value before the ||
operator means you lose the ability of returning the result of f()
. So here's my preferred solution: write a function that behaves like the ||
operator.
// let's call the function "either" so that we can read it as "either f or g"
function either () {
var item;
// return the first non-empty truthy value or continue:
for (var i=0;i<arguments.length;i++) {
item = arguments[i];
if (item.length === 0 || !item) continue
return item;
}
return false;
}
We can now use the either()
function like how we would the ||
operator:
either(f(), g());
Why not simply do the length check at f()
?
function f(){
var returned_array = new Array();
...
if(!returned_array.length)
return false;
}
If you're talking about actually overloading the || operator, you cannot do that in JavaScript (it was proposed back in ECMAScript 4 but rejected). If you really want to do operator overloading in JavaScript, you'd have to use something like JavaScript Shaper, which is "an extensible framework for JavaScript syntax tree shaping" - you could actually use this to overload operators.
精彩评论