【问题标题】:Javascript: reducing down to one numberJavascript:减少到一个数字
【发布时间】:2014-09-24 15:22:01
【问题描述】:

所以我需要取一个日期并通过将每个数字相加将其转换为一个数字,当总和超过 10 时,我需要将两个数字相加。对于下面的代码,我有 12/5/2000,即 12+5+2000 = 2017。所以 2+0+1+7 = 10 & 1+0 = 1。我把它归结为一个数字,它可以工作在 Firebug 中(输出 1)。但是,它在我尝试使用的编码测试环境中不起作用,所以我怀疑有问题。我知道下面的代码很草率,所以任何想法或帮助重新格式化代码都会有所帮助! (注意:我认为它必须是嵌入在函数中的函数,但还不能让它工作。)

var array = [];
var total = 0;

    function solution(date) {
      var arrayDate = new Date(date);
      var d = arrayDate.getDate();
      var m = arrayDate.getMonth();
      var y = arrayDate.getFullYear();
      array.push(d,m+1,y);

        for(var i = array.length - 1; i >= 0; i--) {
          total += array[i];
        };
          if(total%9 == 0) {
            return 9;
          } else
            return total%9;    
    };

solution("2000, December 5");

【问题讨论】:

    标签: javascript arrays modulo


    【解决方案1】:

    你可以只使用递归函数调用

    function numReduce(numArr){
       //Just outputting to div for demostration
       document.getElementById("log").insertAdjacentHTML("beforeend","Reducing: "+numArr.join(","));
       
       //Using the array's reduce method to add up each number
       var total = numArr.reduce(function(a,b){return (+a)+(+b);});
    
       //Just outputting to div for demostration
       document.getElementById("log").insertAdjacentHTML("beforeend",": Total: "+total+"<br>");
       
       if(total >= 10){
          //Recursive call to numReduce if needed, 
          //convert the number to a string and then split so 
          //we will have an array of numbers
          return numReduce((""+total).split(""));
       }
       return total;
    }
    function reduceDate(dateStr){
       var arrayDate = new Date(dateStr);
       var d = arrayDate.getDate();
       var m = arrayDate.getMonth();
       var y = arrayDate.getFullYear();
       return numReduce([d,m+1,y]);
    }
    alert( reduceDate("2000, December 5") );
    &lt;div id="log"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      如果这是您的最终代码,则您的函数不会输出任何内容。试试这个:

      var array = [];
      var total = 0;
      
          function solution(date) {
            var arrayDate = new Date(date);
            var d = arrayDate.getDate();
            var m = arrayDate.getMonth();
            var y = arrayDate.getFullYear();
            array.push(d,m+1,y);
      
              for(var i = array.length - 1; i >= 0; i--) {
                total += array[i];
              };
                if(total%9 == 0) {
                  return 9;
                } else
                  return total%9;    
          };
      
      alert(solution("2000, December 5"));
      

      它会在对话框中提醒结果。

      【讨论】:

        猜你喜欢
        • 2014-06-15
        • 1970-01-01
        • 2022-11-13
        • 2013-05-29
        • 1970-01-01
        • 2017-09-22
        • 2016-01-31
        • 2019-10-12
        • 1970-01-01
        相关资源
        最近更新 更多