首页 > 解决方案 > 如何解决:系统找不到指定的文件 - JS相关的.reduce()

问题描述

编写一个函数,接受一个正参数 num 并返回其乘法持久性,这是您必须将 num 中的数字相乘直到达到单个数字的次数。

例如:939 -> 9*3*9 = 243 -> 2*4*3 = 24 -> 2*4 = 8 // 总计:3 次

我尝试了代码,但它返回:

在 Atom 上:“系统找不到指定的文件。” // 我使用脚本包

在 repl.it 上:“tempoOne.reduce() 不是函数”

`

let persistence = (num) => {

  let tempoOne, tempoTwo;
  let count = 0;
  let changeToString = num.toString();
  let numArray = changeToString.split('');
  var calculator = (accumulator, currentValue) => accumulator*currentValue;

  tempoOne = numArray;

  do {
    tempoOne = tempoOne.reduce(calculator);
    count++;
  } while (tempoOne/10 >= 0);
  return count;
}
console.log(persistence(939));`

标签: javascriptmath

解决方案


把你的tempoOne背对它string进行split迭代:

    let persistence = (num) => {
    
      let tempoOne, tempoTwo;
      let count = 0
      var calculator = (accumulator, currentValue) => accumulator*parseInt(currentValue);

    tempoOne = num;    

      do {
        tempoOne = tempoOne.toString().split('').reduce(calculator, 1);
        count++;
      } while (tempoOne/10 > 1);
      return count;
    }
    console.log(persistence(939));

我注意到您的方法中的一些错误可能会导致一些错误:

  1. 当你split()是一个字符串时,你会得到一个字符串数组,所以你必须在乘以它之前将它解析为 int ,因为你不想乘以字符串(添加parseInt到你的字符串reduce callback中并以中性乘法因子开始:)1
  2. 您不必split跳出循环,因为您希望tempoOne成为循环内的字符串才能split()正常工作(删除了split外循环并添加到循环中)。

推荐阅读