【问题标题】:how to write a function in javascript that transforms multiple of 3 into a string如何在javascript中编写一个将3的倍数转换为字符串的函数
【发布时间】:2019-09-26 17:54:55
【问题描述】:

这是我到目前为止所做的,但是如何创建数字列表以及如何放入循环谢谢:

【问题讨论】:

  • 就参数而言,我相信它们应该在您的for 循环中使用:for (var x=startOfCount; x <= endOfCount; x++)
  • 我在您的问题描述中没有看到"Mojito"
  • 在网上搜索“FooBar 问题”。

标签: javascript function loops if-statement


【解决方案1】:

只需使用包含数组的对象即可返回结果。 另外,必须在循环计数器中安装参数

    function mojitor(startOfCount, endOfCount) {

      var output = {
        menthe : [],
        glace : [],
        rhum : [],
        mentheGlace : [],
        mojito : [],
      };

      for (var x=startOfCount; x <= endOfCount; x++){
          if( x % 3 == 0 ){
              output.menthe.push(x)
          }
          if( x % 5 == 0 ){
              output.glace.push(x)
          }
          if( x % 7 == 0 ){
              output.rhum.push(x)
          }
          if( ( x % 3 == 0 ) && ( x % 5 == 0 ) ){
              output.mentheGlace.push(x)
          }
              if( ( x % 3 == 0 ) && ( x % 5 == 0 )&& ( x % 7 == 0 ) ){
              output.mojito.push(x)
          }
      }
      return output;
    }

    var result = mojitor(1, 110);

    console.log('Menthe: ' + result.menthe); //"Menthe"
    console.log('Glace: ' + result.glace); //"Glace"
    console.log('Rhum: ' + result.rhum); //"Rhum"
    console.log('MentheGlace: ' + result.mentheGlace); //"MentheGlace"
    console.log('Mojito: ' + result.mojito); //"Mojito"

【讨论】:

    【解决方案2】:

    我想你想要这样的东西:

    function mojitor(startOfCount, endOfCount) {
        var items = [];
        for (var x=startOfCount; x <= endOfCount; x++){
            if( ( x % 3 == 0 ) && ( x % 5 == 0 )&& ( x % 7 == 0 ) ){
                items.push("Mojito");
            }
            else if( ( x % 3 == 0 ) && ( x % 5 == 0 ) ){
                items.push("MentheGlace");
            }
            else if( ( x % 3 == 0 ) && ( x % 7 == 0 ) ){
                items.push("MentheRum");
            }
            else if( x % 3 == 0 ){
                items.push("Menthe");
            }
            else if( x % 5 == 0 ){
                items.push("Glace");
            }
            else if( x % 7 == 0 ){
                items.push("Rhum");
            }
            else {
                items.push(x);
            }
        }
        return items;
    }
    
    var numbers = mojitor(1,110);
    
    var line = "";
    var j = 0;
    for(i = 0; i < numbers.length; i++) {
        line += numbers[i] + " ";
        j++;
        if(j === 11){
            console.log(line);
            line = "";
            j = 0;
        }
    }
    if(line != ""){
        console.log(line); //prints the remaining
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多