[英]Array.push throwing TypeError for array.push is not a function
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 显然是一个数组。 为什么推送方法不起作用? 另外,当我将 return 语句更改为
return capitalizeFirst(arr, [].push(str));
并跟随 chrome 调试器,数字 1 不断传递给数组,而不是 arr.pop() 值。 是什么导致了这种行为? 我还没有在实现中添加首字母大写。 这只是我的 push 方法中的一个 replace() 调用,以防有人想知道为什么我的代码没有按照方法名称声明的那样做。
谢谢你的帮助
来自 W3C:
push() 方法将新项添加到数组的末尾,并返回新长度。
第一个循环应该没问题,但是因为你递归地传递.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
}
基本上,你的错误主要是因为push()
在元素被推送到它之后返回数组的长度,这将作为递归调用的参数而不是数组传递:
push() 方法将一个或多个元素添加到数组的末尾并返回数组的新长度。
接下来是一个简单的修复:
function capitalizeFirst(arr, new_arr) { if (arr.length === 0) return new_arr; let str = arr.pop(); // Added code to capitalize first letter. str = str.charAt(0).toUpperCase() + str.slice(1); new_arr.push(str); return capitalizeFirst(arr, new_arr); } console.log(capitalizeFirst(['car','taco','banana'], []));
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
如果你console.log(typeof new_arr)
你得到number
作为答案。
原因是arr.push()
的返回值是该值被推送到的索引,而不是新数组。 所以如果你这样做,你的作品:
function capitalizeFirst(arr, new_arr) {
if (arr.length === 0) return new_arr;
let str = arr.pop();
new_arr.push(str);
return capitalizeFirst(arr, new_arr);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
push() 方法将一个或多个元素添加到数组的末尾并返回数组的新长度。
function capitalizeFirst(arr, new_arr) { console.log("Type of new_arr : ",typeof(new_arr),":", new_arr); if (arr.length === 0) return new_arr; let str = arr.pop(); console.log(str); console.log("Push returns Length", new_arr.push(str)) return capitalizeFirst(arr, new_arr.push(str)); } function correctCapitalizeFirst(arr, new_arr) { console.log("Type of new_arr : ",typeof(new_arr),":", new_arr); if (arr.length === 0) return new_arr; let str = arr.pop(); console.log(str); new_arr.push(str); return correctCapitalizeFirst(arr, new_arr); } console.log("--------------- Correct -----------------"); correctCapitalizeFirst(['car','taco','banana'], []); console.log("--------------- Incorrect ---------------"); capitalizeFirst(['car','taco','banana'], []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.