D
D
dmptts2018-02-17 21:31:58
JavaScript
dmptts, 2018-02-17 21:31:58

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]));

Why in this example does the object with i = 1 not close on itself and become something like
{value: 20, rest: {value: 20, rest: {value: 20, rest: null}}}...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-17
@dmptts

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;

First, the right side is calculated, then the assignment occurs: or: And this is how you can make a reference to yourself:
var obj = {       // создаем объект доступный по ссылке obj
  prop: 'example prop' 
};

obj.self = obj;  // добавляем в объект свойство self ссылающееся на сам объект

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question