Javascript:减少到一个数字

Javascript: reducing down to one number

本文关键字:一个 数字 Javascript      更新时间:2023-09-26

所以我需要取一个日期,并通过将每个数字相加将其转换为一个数字,当总和超过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");

您可以使用一个递归函数调用

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") );
<div id="log"></div>

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

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"));

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