开发者

What does ? : mean in Javascript? [duplicate]

This question already has answers here: 开发者_开发百科 Question mark and colon in JavaScript (8 answers) Closed 7 years ago.

What does this line of code do?

len = ( s.length>t.length ) ? s.length : t.length


?: is the ternary operator. It returns a value based on a condition.

x = (condition)?(if-true):(if-false)

So if condition is true, x is the value in the if-true section, and if it's false, then x is the value in if-false.

If is equivalent to what Corv1nus said earlier.


It's the equivalent of len = Math.max( s.length, t.length ); using the ternary conditional operator.


It sets the variable len to the length of string s, or the length of string t, depending on which is longer.


If s.length is greater than t.length set len = s.length else set len = t.length


That is using the conditional operator, which is also known as a ternary because it takes three operands.

See https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Conditional_Operator for more info.

You can find this construct with the same syntax in PHP, C, C++ and other languages, too.


it is the equivalent of:

var len=0;
if(s.length>t.length)
  len= s.length;
else
  len=t.length;

So it's just a short way do doing if else.


len will be assigned the length of either s or t depending on which one has a greater length


It is doing this:

if (s.length > t.length) {
    len = s.length;
} else {
    len = t.length;
}


If the length of s is greather than the length of t, make "len" the length of s. If the length of s is less than or equal to the length of t, make "len" the length of t.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜