I am given a list -
let listA = {value: 10, rest: {value: 20, rest: { value: 30, rest: null }}}
I need to convert it into an array -
[10, 20, 30]
I used this for loop to go over the keys in list
It did not work. Eloquent JS book uses this for loop -
let array = [];
for (let node = list; node; node = node.rest){
array.push(node.value);
I am a beginner. I have only encountered simple for loops such as -
for(let i=0; i <= array.length; i )
and similar versions.
Can someone please explain this for loop syntax ?
This for loop works but don't know how
CodePudding user response:
Your "list" is a linked list. It is modeled as recursively nested objects. You need either a recursive algorithm or keep track of your current "stack" manually when writing in iterative form.
let array = [];
for (let node = list; node; node = node.rest) {
array.push(node.value);
}
Takes the first object, pushes it into the array, then lets the current object point to node.rest
(the inner, nested object) and repeats this until the current object no longer points anywhere (node
is shorthand for !!node
: it tests the value to be truthy. Not quite right, but you can think of it as node != null
).
If you are not accustomed to non-indexed for-loops, it can easily be translated into a while loop with the same behavior:
let array = [];
let node = list;
while (node) { // shorthand for `!!node`: tests the value to be truthy
array.push(node.value);
node = node.rest;
}
The variable node
assumes the following values in order:
{ value: 10, rest: { value: 20, rest: { value: 30, rest: null } } }
{ value: 20, rest: { value: 30, rest: null } }
{ value: 30, rest: null }
null
CodePudding user response:
Your input object is nested json object with value key and rest as next object.
{value: 10, rest: {value: 20, rest: { value: 30, rest: null }}}
For loop that you have put is iterating over the nested object
In first iteration it takes the root object pushing value 10 to the array.
In 2nd iteration it takes the first nested object reading value 20 and it pushes it to the array.
In 3rd iteration it reads next nested object and pushes value 30 to the array.