简体   繁体   中英

Can someone explain this line of code? 0 % 2

Was working through the following problem:

function padIt accept 2 parameters:

1. str , it's a string representing the string to pad, we need to pad some "*" at leftside or rightside of str

2. n , it's a number, how many times to pad the string.

This is the answer:

function padIt(str,n){
  var count = 0;
  while ( count < n ) {
    count % 2 ? str += '*' : str = '*' + str;
    count ++
  }
  return str;
}

Can someone explain this part? count % 2 ? str += '*' : str = '*' + str;

Say I put these parameters in the function, padIt('a', 1) The first loop will have count = 0 so the function will have 0 % 2 which = 0 . Why does the function choose the option str = '*' + str to output '*a' ? Why not str += '*' to output 'a*' ?

This is a one-line shorthand for an if-else statement. It's called the conditional(ternary) operator.

 function padIt(str,n){
  var count = 0;
  while ( count < n ) {
    count % 2 ? str += '*' : str = '*' + str;
    count ++
   }
    return str;
  }

This is construct count % 2 ? str += '*' : str = '*' + str; count % 2 ? str += '*' : str = '*' + str; is the same as

      if(count % 2){
          str += '*';
       }else{

         str = '*' + str;
       }


count % 2 ? str += '*' : str = '*' + str; means if count is even do this if not do that.
The obvious advantage is that is it's shorter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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