JavaScript add to object array — why reverse the order?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
36 views
Good afternoon.
Tell on your toes, if not laziness - why add array element into the tree from the bottom up?
var arrayToList = function(array){ var list = null; for (i = array.length-1; i >= 0;i--){ list = {value:array[i], next:list}; console.log(array[i]); } return list; } console.log(arrayToList([10,20,30,40,50]));


can't understand the logic... the idea is have a top-down, i.e. the tree should be:
50
-40
--30
---20
----10

or is it because recursion works? If so, why?
by | 36 views

2 Answers

0 like 0 dislike
Where you here saw recursion? You iterate through the array is the last element.
by
0 like 0 dislike
The answer here:
for (i = array.length-1...
In the first iteration you add the last element of the array.
With the next - the penultimate and so on to the first.

If you need reverse order, the cycle parameters should be approximately such:
for (var i = 0; i <= array.length-1 ; i++)
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked May 10, 2019 by Tolly
0 like 0 dislike
1 answer
110,608 questions
257,187 answers
0 comments
40,796 users