Javascript 从 1 到 100,如果是 3 的倍数,则打印“ping”,如果是 5 的倍数,则打印“pong”,否则打印数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13845437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:55:22  来源:igfitidea点击:

From 1 to 100, print "ping" if multiple of 3, "pong" if multiple of 5, or else print the number

javascriptfizzbuzz

提问by BernaMariano

I just came home from a job interview, and the interviewer asked me to write a program:

我刚面试完回家,面试官让我写一个程序:

It should, count from 1 to 100, and print...

它应该从 1 数到 100,然后打印...

If it was multiple of 3, "ping"
If it was multiple of 5, "pong"
Else, print the number.

如果是 3 的倍数,“ping”
如果是 5 的倍数,“pong”
否则,打印数字。

If it was multiple of 3 AND 5 (like 15), it should print "ping" and "pong".

如果它是 3 AND 5 的倍数(比如 15),它应该打印“ping”和“pong”。

I chose Javascript, and came up with this:

我选择了 Javascript,并想出了这个:

for (x=1; x <= 100; x++){
    if( x % 3 == 0 ){
        write("ping")
    }
    if( x % 5 == 0 ){
        write("pong")
    }
    if( ( x % 3 != 0 ) && ( x % 5 != 0 ) ){
        write(x)
    }
}

Actualy, I left very unhappy with my solution, but I can't figure out a better one.

实际上,我对我的解决方案非常不满意,但我想不出更好的解决方案。

Does anyone knows a better way to do that? It's checking twice, I didn't like it. I ran some tests here at home, without success, this is the only one that returns the correct answer...

有谁知道更好的方法来做到这一点?它检查了两次,我不喜欢它。我在家里在这里进行了一些测试,但没有成功,这是唯一返回正确答案的测试...

回答by Fabrício Matté

Your solution is quite satisfactory IMHO. Tough, as half numbers are not multiple of 3 nor 5, I'd start the other way around:

恕我直言,您的解决方案非常令人满意。艰难,因为半数既不是 3 也不是 5 的倍数,我会反过来说:

for (var x=1; x <= 100; x++){
    if( x % 3 && x % 5 ) {
        document.write(x);
    } else {
        if( x % 3 == 0 ) {
            document.write("ping");
        }
        if( x % 5 == 0 ) {
            document.write("pong");
        }
    }
    document.write('<br>'); //line breaks to enhance output readability
}?

Fiddle

小提琴

Also, note that any number other than 0and NaNare truthy values, so I've removed the unnecessary != 0and some pairs of parenthesis.

另外,请注意,除0and之外的任何数字NaN都是真值,因此我删除了不必要!= 0的括号和一些括号对。



Here's another version, it doesn't make the same modulus operation twice but needs to store a variable:

这是另一个版本,它不会进行两次相同的模数运算,但需要存储一个变量:

for (var x=1; x <= 100; x++) {
    var skip = 0;
    if (x % 3 == 0) {
        document.write('ping');
        skip = 1;
    }
    if (x % 5 == 0) {
        document.write('pong');
        skip = 1;
    }
    if (!skip) {
        document.write(x);
    }
    document.write('<br>'); //line breaks to enhance output readability
}

Fiddle

小提琴

回答by Shmiddty

Here's my one-liner:

这是我的单线:

for(var x=1;x<101;x++)document.write((((x%3?'':'ping')+(x%5?'':'pong'))||x)+'<br>');

? I'm using ternary operators to return either an empty string or 'ping'/'pong', concatenating the result of these operators, then doing an OR (if the number is neither divisible by 3 or 5, the result of the concatenation is ''which is FALSEY in javascript). When both cases are true, the result of the concatenation is 'pingpong'.

? 我正在使用三元运算符返回一个空字符串或'ping'/'pong'连接这些运算符的结果,然后执行 OR(如果数字既不能被 3 或 5 整除,则连接的结果''在 javascript 中为 FALSEY)。当两种情况都为真时,串联的结果是'pingpong'

So basically it comes down to

所以基本上归结为

'' || x         // returns x
'ping' || x     // returns 'ping'
'pong' || x     // returns 'pong'
'pingpong' || x // returns 'pingpong'

回答by TheSETJ

The best solution I came up with is this one:

我想出的最佳解决方案是:

for (var i = 1; i <= 100; i++) {
  var message = '';
  if (i%3 === 0) message += 'ping';
  if (i%5 === 0) message += 'pong';
  console.log(message || i);
}

回答by SomeGuy

Here's a solution which allows for a dynamic list of multiples without adding more conditionals.

这是一个允许动态倍数列表而不添加更多条件的解决方案。

// List of outputs
var outputs = [
    {mult: 3, str: 'ping'},
    {mult: 5, str: 'pong'}
    // {mult: 10, str: 'play'} ex: [30] => 'pingpongplay'
];

// Loop 100 times
for (var i = 1, j = 100; i <= j; i += 1) {

    // Set empty vars
    var result, string = '';

    // Loop through the listed output objects
    outputs.forEach(function (output) {

        // If listed multiple, concat string
        if (i % output.mult === 0) {
            string += output.str;
        }

    });

    // Set result
    if (string.length) {
        result = string;
    } else {
        result = i;
    }

    // print result
    document.body.innerHTML += result + '<br>';
}

And as a function which passes jslint:

并作为传递 jslint 的函数:

/*jslint browser: true */
var printOutputs = function (array, iterations) {
    'use strict';
    var i = 1;
    var outputResults = function (arr, idx) {
        var result;
        var str = '';
        arr.forEach(function (item) {
            if (idx % item.mult === 0) {
                str += item.str;
            }
        });
        if (str.length) {
            result = str;
        } else {
            result = idx;
        }
        return result;
    };
    while (i < iterations) {
        document.body.innerHTML += outputResults(array, i) + '<br>';
        i += 1;
    }
};
var outputs = [
    {mult: 3, str: 'ping'},
    {mult: 5, str: 'pong'}
];
printOutputs(outputs, 100);

And for fun, a minified ES6 version:

为了好玩,一个缩小的 ES6 版本:

const pO=(arr,itr)=>{let i=1,o=(a,idx)=>{let r,s='';a.map(v=>{if(idx%v.mult===0)s+=v.str});s.length?r=s:r=idx;return r};while(i<itr){document.body.innerHTML+=`${o(arr,i)}<br>`;i++}};
pO([{mult:3,str:'ping'},{mult:5,str:'pong'}], 100);

回答by Sambydev

//create a for loop to count from 0 to 100
       for (let num = 0; num <= 100; num++){
        /**As the count increments, if the number is divisible by 3 and divisible by 5
        print FizzBuzz, I have concatenated the number with FizzBuzz for clarity. 
        Use % instead of \ to ensure it returns an int instead of float.**/
         if ((0 == num % 3) && (0 == num % 5)){
           console.log ("FizzBuzz" + " " + num); 
//otherwise, if the number is divisible by 5 print Buzz
         } else if (0 == num % 5) {
          console.log("Buzz" + " " + num);
//Also, if the number is divisible by 3 print Fizz
         } else if (0 == num % 3){
           console.log("fizz" + " " + num);
         } else {
//meanwhile, still print all the numbers that don't satisfy the conditions above
           console.log (num);
         }
      }

回答by Benny

I wrote a few variations on this (using fizzand buzz) as a benchmark to consider different ways of iterating over conditional logic.

我对此写了一些变体(使用fizzbuzz)作为基准来考虑迭代条件逻辑的不同方式。

whilewon again:

while又赢了:

// Iterate using a recursive function
// firing a callback once per iteration

function f(s,n) {
    if(++n >= 102) return;
    s === '' ? console.log(n-1) : console.log(s);
    !!(n % 3)
        ? !!(n % 5)
            ? f('',n) : f('Buzz',n)
        : !!(n % 5)
            ? f('Fizz',n) : f('FizzBuzz',n);
}

// Iterate using a `while` loop
// firing a callback after satisfying a condition

function b(n) {
    var i = n;
    $:
        while(++i) {
            if(i % 3)
                if(i % 5) 
                    console.log(i);
                else 
                    console.log('Buzz');
            else if(i % 5) 
                console.log('Fizz');
            else 
                console.log('FizzBuzz');
            if(i >= 100) 
                break $;
        }
    return;
}

// Iterate using a `for` loop
// firing a callback once per iteration

function F(n) {
    var i = n, f = 'Fizz', b = 'Buzz', o = '';
    for (; i <= 100; i++) { 
        o = !(i % 3) 
            ? !(i % 5) 
                ? f + b : f 
            : !(i % 5) 
                ? b : i; 
        console.log(o);
    }
    return;
}

// Iterate using a `for` loop
// firing a callback after satisfying a condition

function B(n) {
    var i = n;
    var fiz = 'Fizz';
    var buz = 'Buzz';
    for(; i <= 100; i++)
        if(!(i % 3))
            if(!(i % 5))
                console.log(fiz + buz);
            else
                console.log(fiz);
        else if(!(i % 5))
            console.log(buz);
        else
            console.log(i);
    return;     
}


f('', 1); // recursive
b(0);     // `while`
F(1);     // `for`
B(1);     // `for

Benchmark: http://jsperf.com/fizzbuzz-mod

基准:http: //jsperf.com/fizzbuzz-mod

回答by Qaiser Habib

 for( int number = 1 ; number < 100 ; number++ )
    {
        boolean shouldPrintNumber = true;

        System.out.println("\n");
        if( (number%3) == 0 )
        {
            System.out.print("ping");
            shouldPrintNumber = false;
        }
        if( (number%5) == 0 )
        {
            System.out.print("pong");
            shouldPrintNumber = false;
        }

        if( shouldPrintNumber )
        {
            System.out.print( number );
        }

    }

回答by Sathya Jayagopi

for var a = 1; a <= 100 ; a++
{
  if a % 3 == 0 && a % 5 == 0
  {
    println("Fizzbuzz")
    continue
  }
  if a % 5 == 0
  {
    println("Buzz")
    continue
  }
  if a % 3 == 0
  {
    println("Fizz")
    continue
  }
  else
  {
    println(a)
  }
}

回答by powtac

To get rid of the last condition you might use continue:

要摆脱您可能使用的最后一个条件continue

for (x=1; x <= 100; x++){

    if( x % 3 == 0 ){
        write("ping")
        continue
    }
    if( x % 5 == 0 ){
        write("pong")
        continue
    }

    write(x)
}