-1

I had seen this question on an interview a few months ago, but I wanted to confirm my answer.

(I'm writing a blog post of past interview questions to clarify my answers.)

if (foo) { bar.doSomething(el); }
else { bar.doSomethingElse(el); }

Answer:

foo ? bar.doSomething(el) : bar.doSomethingElse(el);
4

1 回答 1

2

你也可以这样写(可读性稍差):

(foo ? bar.doSomething : bar.doSomethingElse)(el);

甚至是病态的,虽然更短:

bar[foo ? 'doSomething' : 'doSomethingElse'](el);

可以进一步压缩(在您的示例中)为:

bar['doSomething' + (foo ? '' : 'Else')](el);

如果你真的想摆脱条件,你可以做一些鬼鬼祟祟的事情,比如:

bar[['doSomething', 'doSomethingElse'][+!!foo]](el);
于 2013-06-05T04:36:35.717 回答