提问人:Ashy Ashcsi 提问时间:7/31/2022 最后编辑:JMPAshy Ashcsi 更新时间:7/31/2022 访问量:426
在 JavaScript 的递归函数中按值传递 [duplicate]
pass by value in recursive function in javascript [duplicate]
问:
计算数字中零个数的递归解决方案如下:
const number = 3004;
const countZeroes = function (num) {
if (num == 0) {
return;
}
if (num % 10 == 0) {
count += 1;
}
countZeroes(parseInt(num / 10));
}
let count = 0;
countZeroes(3004);
console.log('the result ', count);
当我们使用 count 作为全局变量时,上述解决方案工作正常。但是,当 count 作为参考变量传递时,它不起作用。请在下面找到解决方案:
const number = 3004;
const countZeroes = function (num, count) {
if (num == 0) {
return count;
}
if (num % 10 == 0) {
count += 1;
}
countZeroes(parseInt(num / 10));
}
let count = 0;
const result = countZeroes(3004, count);
console.log('the result ', result);
javascript 是否只允许按值传递,而不允许按引用传递。请告诉我。
答: 暂无答案
评论
return countZeroes(...)
return countZeroes(parseInt(num / 10), count);