循环计数到100,并将能被3整除或包含数字3的任何数字替换为某些文本。

huangapple go评论82阅读模式
英文:

loop that count to 100 and replace with some text any number that divide by 3 or conatins number 3

问题

function checker(num) {
  for (i = 1; i <= num; ++i) {
    if (i % 3 === 0 || i.toString().includes('3')) {
      console.log('boom');
    } else {
      console.log(i);
    }
  }
}
checker(100);
英文:
function checker (num){
  for(i = 1; i &lt;= num; ++i){
    if(i % 3 === 0 ||
       i === 13 ||
        i === 23 ||
         i === 33 ||
          i === 43 ||
           i === 53 ||
            i === 63 ||
             i === 73 ||
              i === 83 || 
              i === 93){
      console.log(&#39;boom&#39;)
    }
    else{
      console.log(i)
    }
  }
}
checker(100)

so i made this , but thats looks ugly , how to do it correct ? like any number that contains 3 replace it with some text. thank you.

答案1

得分: 2

你可以检查字符串,也可以检查以下部分。

if (i % 3 === 0 || i.toString().includes('3')) ...
英文:

You could check the string, too.

if (i % 3 === 0 || i.toString().includes(&#39;3&#39;)) ...

答案2

得分: 1

If your loop only counts to 100, you only need to check the tens and ones place to determine if it's a 3. You can use the JavaScript modulo operator % and the Math.floor() static method:

if (Math.floor(i / 10) === 3 || i % 10 === 3 || i % 3 === 0) // ...

The Math.floor method will return true if dividing the number by 10 and rounding down returns 3 (true for the numbers 30 to 39 inclusive), and the % modulo operator will return true when dividing i by 10 has a remainder of 3 (true for 3, 13, 23, 33, etc.) i % 3 === 0 is from your original function.

英文:

If your loop only counts to 100, you only need to check the tens and ones place to determine if it's a 3. You can use the JavaScript modulo operator % and the Math.floor() static method:

if (Math.floor(i / 10) === 3 || i % 10 === 3 || i % 3 === 0) // ...

The Math.floor method will return true if dividing the number by 10 and rounding down returns 3 (true for the numbers 30 to 39 inclusive), and the % modulo operator will return true when dividing i by 10 has a remainder of 3 (true for 3, 13, 23, 33, etc.) i % 3 === 0 is from your original function.

huangapple
  • 本文由 发表于 2023年2月16日 01:55:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75463697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定