[英]How to fix ‘TypeError: arr.map is not a function’ error in Javascript
I am doing a Hackerrank challenge 'Manasa and Stones' 我正在向Hackerrank挑战“ Manasa and Stones”
I have already done an Looping solution but it took to much time solving tree levels and I need a recursive solution I guess. 我已经完成了Looping解决方案,但是解决树级别花费了很多时间,我需要一个递归解决方案。
function stones(n, a, b) {
var arr = [0,0];
var rresult = recursive(0,a,b,arr,n)
return rresult;
}
function recursive(n,a,b,arr,end){
if (n == end){ return arr }
else {
let arr2 = arr.map(function(x) {
return x * 2;
});
arr = arr.map(function(x) {
return x * 2;
});
arr = arr.join(arr2)
recursive(n,a,b,arr,end)
}
}
It should be working as expected to solve https://www.hackerrank.com/contests/microverse-coding-challenges/challenges/manasa-and-stones/problem (I don't from expect you to do a solution I need to know why my issue is there * It doesn't make sense) 它应该能够按预期的方式解决https://www.hackerrank.com/contests/microverse-coding-challenges/challenges/manasa-and-stones/problem (我不是希望您做我需要的解决方案知道为什么我的问题在那里*没有道理)
all my code => https://github.com/Macatuz/MHackerrankSamples/blob/master/Manasa_and_Stones.js 我所有的代码=> https://github.com/Macatuz/MHackerrankSamples/blob/master/Manasa_and_Stones.js
arr = arr.join(arr2)
is not doing what you think it does--the .join
method joins the elements in an array into a string delimited by the parameter. arr = arr.join(arr2)
没有做什么,你认为它-的.join
方法加入在数组中的元素到由参数分隔的字符串。 When you pass this string arr
into the recursive function call, you'll get a crash on the next stack frame, because strings don't have a map
function. 当您将此字符串
arr
传递给递归函数调用时,您会在下一个堆栈帧上崩溃,因为字符串没有map
函数。
You probably meant .concat
, which puts the elements from the parameter array on the back of the instance array. 您可能是说
.concat
,它将参数数组中的元素放在实例数组的背面。 Here's a snippet to illustrate what's going on. 这是一个片段来说明正在发生的事情。
const arr1 = ["apples", "bananas"]; const arr2 = ["celery", "asparagus"]; const joined = arr1.join(arr2); const concatted = arr1.concat(arr2); console.log(joined, typeof joined); // whoops? console.log(concatted); // ah. much better.
Note that this only solves the query in your title but doesn't produce working code that solves the challenge--that's an exercise for the reader. 请注意,这只会解决标题中的查询,而不会产生解决挑战的有效代码-这是读者的练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.