簡體   English   中英

如何打印 function 的返回值?

[英]How do I print the return value of a function?

我正在嘗試打印 function 的返回值,但我似乎做不到。 最后一行我一直undefined

let count = 0;
   
   
   function product(num){
     let result = 1;
     strNum = num.toString()
     strNumArr = strNum.split("")
     
     if(strNum.length === 1){
       return count;
     }
     
     
     for(let i = 0; i< strNum.length; i++){
       result *= parseInt(strNumArr[i])  
     }
     count++;
     //console.log(count)
     product(result)
   }
  
 let bool = product(39);
 console.log(product(39));

我知道我缺少一些基本的東西,但我不知道它是什么。

如果我理解您要正確實現的目標,這是您的代碼的工作版本。

 function product(num){ let result = 1; strNum = num.toString() strNumArr = strNum.split("") if(strNum.length === 1){ return num; } for(let i = 0; i< strNum.length; i++){ result *= parseInt(strNumArr[i]) } return result; } console.log(product(39)); // should return 27 console.log(product(5)); // should return 5 console.log(product(234)); // should return 24

完成循環后,您應該返回result

順便說一句,同樣可以用一個襯里來實現。 例如

function product(num) { 
    return Array.from(String(num).split('')).reduce((c,p) => p * c, 1)
}

替換product(result)return product(result) 這樣,如果 function 調用自身,它會返回嵌套 function 調用中生成的值。

let count = 0;
   
   
   function product(num){
     let result = 1;
     strNum = num.toString()
     strNumArr = strNum.split("")
     
     if(strNum.length === 1){
       return count;
     }
     
     
     for(let i = 0; i< strNum.length; i++){
       result *= parseInt(strNumArr[i])  
     }
     count++;
     //console.log(count)
     return product(result)
   }
  
 let bool = product(39);
 console.log(product(39));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM