2014-09-24 64 views
0

所以我需要把一個日期,並將其轉換成一個單一的數字加起來每個數字,當總和超過10,我需要加起來的兩個數字。對於下面的代碼,我有12/5/2000,這是12 + 5 + 2000 = 2017。所以2 + 0 + 1 + 7 = 10 & 1 + 0 = 1.我把它歸結爲一個數字,它的工作原理在Firebug中(輸出1)。但是,它不是在我嘗試使用的編碼測試環境中工作,所以我懷疑有些問題。我知道下面的代碼是草率的,所以任何想法或幫助重新格式化代碼將會很有幫助! (注:我想它是一個函數嵌入功能,但一直沒能得到它的工作還沒有。)Javascript:減少到一個數字

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

回答

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

0

如果這是你最後的代碼的功能沒有任何輸出。試試這個:

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

它會提醒對話框中的結果。