javascript - 如何解决:系统找不到指定的文件 - 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));`
解决方案
把你的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));
我注意到您的方法中的一些错误可能会导致一些错误:
- 当你
split()
是一个字符串时,你会得到一个字符串数组,所以你必须在乘以它之前将它解析为 int ,因为你不想乘以字符串(添加parseInt
到你的字符串reduce callback
中并以中性乘法因子开始:)1
。 - 您不必
split
跳出循环,因为您希望tempoOne
成为循环内的字符串才能split()
正常工作(删除了split
外循环并添加到循环中)。
推荐阅读
- python - 当累积和达到阈值时,Pandas 新列可查找
- javascript - 如何使用 chart.js 和 chartjs-node-canvas 在 PDF 中的条形顶部显示值?
- python - 带有缩进错误的 Python3 多部分电子邮件脚本问题
- typescript - 如何扩展keyof 类型,使其包含修改后的键版本,例如以'-' 为前缀?
- selenium - 可以像使用 Selenium/Protractor 一样在 Chrome 开发工具中测试上传文件吗?
- azure - 如何在 Azure DevOps 中迁移共享查询
- xml - 如何在 shell 脚本中提取 XML 数据?
- javascript - 尝试播放音频文件时出现错误“无法读取属性 isPlaying”
- python - Python TypeError:(“'NoneType'类型的对象没有len()”
- javascript - 有什么方法可以突出显示文本