Answer the question
In order to leave comments, you need to log in
Why doesn't an object refer to itself?
Good afternoon!
I'm in the process of learning JS from Expressive Javascript and can't figure out how to solve one of the problems in the section on arrays and objects.
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
};
console.log(arrayToList([10, 20]));
{value: 20, rest: {value: 20, rest: {value: 20, rest: null}}}...
Answer the question
In order to leave comments, you need to log in
The list
variable is initially set to null . Then, each iteration, the code is executed:
First, the right side of the expression is executed, an object is created with the value property taking the value of the array element at index i , and the rest property taking the value list , the first iteration it is null :
Well, then the created object is assigned to the variable list . And so every iteration.
A simple example of how it works:
var x = 10;
x = x + 5;
var obj = { // создаем объект доступный по ссылке obj
prop: 'example prop'
};
obj.self = obj; // добавляем в объект свойство self ссылающееся на сам объект
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question