javascript - Choose function according to ternary operators - Stack Overflow

I've a code:a=function(x){alert(x)}b=function(x){document.write(x)}c=1;[c==1?a:b](':p'

I've a code:

a=function(x){alert(x)}
b=function(x){document.write(x)}
c=1;
[c==1?a:b](':p');

but it's not working. Is possible to do what I want?

I've a code:

a=function(x){alert(x)}
b=function(x){document.write(x)}
c=1;
[c==1?a:b](':p');

but it's not working. Is possible to do what I want?

Share Improve this question asked Dec 9, 2013 at 17:39 user3073240user3073240 6031 gold badge6 silver badges9 bronze badges 1
  • 3 Why do people like to write such unreadable code? For goodness sakes, use an if/else and make your code reaadable. If you want small size, then minimized it afterwards. My priorities are "correct", "readable/maintainable", "pact", "fast". Only on a very few occasions (usually after detailed performance profiling) is it worth sacrificing either of the first two for speed or size. – jfriend00 Commented Dec 9, 2013 at 17:47
Add a ment  | 

1 Answer 1

Reset to default 11

Yes, just replace the square brackets with parentheses. You are creating an array literal, but you want to isolate an expression:

(c==1?a:b)(':p');

This would also work, but there is no reason to use it:

[c==1?a:b][0](':p');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745402761a4626176.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信