There is a problem when the getFirstHalf function returns the result
P粉311617763
P粉311617763 2023-09-22 08:49:09
0
1
682

I'm developing a function that takes an array and returns the first half of the array, but before returning it calls itself until the length of the array is 1:

const getFirstHalf = function (array) { const firstHalf = []; for (let i = 0; i < Math.trunc(array.length / 2); i++) { firstHalf.push(array[i]); } if (firstHalf.length !== 1) { getFirstHalf(firstHalf); } return firstHalf; };

Everything works as expected, until the row where the result is returned, the array gets the previous value until it is the first half of the first state of the array. Hope you understand what I mean.

For example:

const myArray = [1,2,3,4,5,6,7,8]; console.log(getFirstHalf(numbers));

I expected to get [1] as result, but I got [1,2,3,4].

P粉311617763
P粉311617763

reply all (1)
P粉009186469

You need to return the result from the recursion:

Will

getFirstHalf(firstHalf);

changed to

return getFirstHalf(firstHalf);
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!