【问题标题】:How do I print the return value of a function?如何打印函数的返回值?
【发布时间】:2021-01-09 21:55:17
【问题描述】:

我正在尝试打印函数的返回值,但我似乎做不到。最后一行我不断收到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));

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

【问题讨论】:

  • 你的函数应该做什么? count 变量的用途是什么?

标签: javascript function return


【解决方案1】:

如果我理解您要正确实现的目标,这里是您的代码的工作版本。

   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)
}

【讨论】:

    【解决方案2】:

    product(result) 替换为return product(result)。这样,如果函数调用自身,它会返回嵌套函数调用中生成的值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2020-01-29
      • 2015-12-01
      • 2018-08-28
      • 2020-01-26
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多