为什么即使在for循环之前就已声明fin变量也未定义?
a = function(...args) {
total = 0;
for (each of args) {
total += each;
}
total = total.toString();
while (total.length != 1) {
var fin = 1;
for (int i = 0; i < total.length; i++) {
fin *= parseInt(total[i]);
}
total = fin.toString();
}
return parseInt(fin);
}
a(1,2,3,4,5,6)
答案 0 :(得分:2)
如果我删除了您所有的int
引用,它将运行正常
a = function(...args) {
total = 0;
for (each of args) {
total += each;
}
total = total.toString();
while (total.length != 1) {
var fin = 1;
for (i = 0; i < total.length; i++) {
fin *= parseInt(total[i]);
}
total = fin.toString();
}
return parseInt(fin);
}
var result = a(1,2,3,4,5,6);
console.log('result', result);
[edit]如果我想以更多方式修复它,我可能会这样写:
const a = function(...args) {
let total = 0;
for (let each of args) {
total += each;
}
total = total.toString();
let fin;
while (total.length != 1) {
fin = 1;
for (let i = 0; i < total.length; i++) {
fin *= parseInt(total[i]);
}
total = fin.toString();
}
return parseInt(fin);
}
var result = a(1,2,3,4,5,6);
console.log('result', result);
答案 1 :(得分:2)
您使用的int
关键字以及一些未定义的int
对象不存在。您要尝试的是这样:
a = function(...args) {
total = 0;
for (each of args) {
total += each;
}
total = total.toString();
while (total.length != 1) {
var fin = 1;
for (let i = 0; i < total.length; i++) {
fin *= parseInt(total[i]);
}
total = fin.toString();
}
return parseInt(fin);
}
console.log(a(1,2,3,4,5,6));
答案 2 :(得分:0)
要使此代码正常工作,您需要做几处更改。
JavaScript不会理解诸如 int 之类的东西(因为它不是强类型的),因此在for循环中删除int关键字并改用let或var。
对于( let ,i = 0; i
您必须使用fin * = Number.parseInt(total [i]);
来代替 int.parseInt