简体   繁体   English

有人可以解释这行代码吗? 0 % 2

[英]Can someone explain this line of code? 0 % 2

Was working through the following problem:正在解决以下问题:

function padIt accept 2 parameters:函数padIt接受 2 个参数:

1. str , it's a string representing the string to pad, we need to pad some "*" at leftside or rightside of str 1. str ,它是一个表示要填充的字符串的字符串,我们需要在str左侧或右侧填充一些"*"

2. n , it's a number, how many times to pad the string. 2. n ,它是一个数字,填充字符串的次数。

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 .假设我将这些参数放在函数padIt('a', 1) ,第一个循环将有count = 0所以该函数将有0 % 2 which = 0 Why does the function choose the option str = '*' + str to output '*a' ?为什么函数选择选项str = '*' + str来输出'*a' Why not str += '*' to output 'a*' ?为什么不str += '*'输出'a*'

This is a one-line shorthand for an if-else statement.这是 if-else 语句的单行简写。 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; 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.明显的优点是它更短。

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

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