简体   繁体   English

在JavaScript中使用三元

[英]Using ternary in JavaScript

Is there a shorter way to write this? 有没有更短的写方法?

var ttt = "dd";
if (ttt.length < 3) 
ttt= "i" + ttt;

Yours is pretty short, but if you want to use the the conditional operator (aka the ternary operator), you could do the following: 您的代码很短,但是如果要使用条件运算符 (也称为三元运算符),则可以执行以下操作:

var ttt = "dd";
ttt = ttt.length < 3 ? "i" + ttt : ttt;

... or if bytes are really precious (code golfing?), you could also do something like this: ...或者如果字节真的很宝贵(代码打高尔夫球?),您还可以执行以下操作:

var ttt = "dd".length < 3 ? "i" + "dd" : "dd";

... but then that could be reduced to just: ...但是那可以简化为:

var ttt = "idd";

... as @Nick Craver suggested in a comment below. ...就像@Nick Craver在下面的评论中建议的那样。

The shortest with the same result is: 结果最短的是:

var ttt="idd";

because "dd" has a length of 2. so the if is always true and you'll always prepend "i" 因为“ dd”的长度为2,所以if始终为true,并且您将始终以“ i”开头

Another option is to use a regex: 另一种选择是使用正则表达式:

var ttt = "dd".replace(/^(\w?\w?)$/, 'i$1');

But then you have 2 problems :) 但是,那么你有两个问题:)

Or : 要么 :

var ttt = "dd";
ttt = (ttt.length < 3 ? i : "") + ttt;

Also there's a way with && operator instead of if 还有一种&&运算符代替if

var ttt = "dd";
ttt.length < 3 && (ttt = "i" + ttt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM