function capitalizeFirst(arr, new_arr) {
if (arr.length === 0) return new_arr;
let str = arr.pop();
console.log(str);
return capitalizeFirst(arr, new_arr.push(str));
}
这是我的代码。目标是通过此练习练习递归。我给函数以下参数
capitalizeFirst(['car','taco','banana'], []);
new_arr 显然是一个数组。为什么 push 方法不起作用?另外,当我将返回语句更改为
return capitalizeFirst(arr, [].push(str));
然后使用 chrome 调试器,数字 1 一直传递给数组而不是 arr.pop() 值。是什么导致了这种行为?我还没有在实现中添加首字母大写。这只是我的 push 方法中的 replace() 调用,以防有人想知道为什么我的代码没有执行方法名称所声明的内容。
感谢您的帮助
最佳答案
来自 W3C:
The push() method adds new items to the end of an array, and returns the new length.
第一个循环应该没问题,但是因为您递归地传递 .push
,第二个循环看到的是一个数字而不是一个数组,因为 push
返回一个数字。
推送它自己的行,然后只传递 new_arr 作为参数。
function capitalizeFirst(arr, new_arr) {
if (arr.length === 0) return new_arr;
let str = arr.pop();
console.log(str);
new_arr.push(str); // the return of .push is the array length, which is not needed.
return capitalizeFirst(arr, new_arr); // pass the full array into this function, making it recursive
}
关于javascript - Array.push throw TypeError for array.push is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423187/