Answer the question
In order to leave comments, you need to log in
Why, when assigning the value of variable "1" to variable "2", variable "2" is replaced by "1"?
Good day, in general, I am self-taught, I am making a telegram bot on Node.JS.
I am implementing the possibility of placing an order, but in the process there was a problem that I do not understand how to solve.
You need to assign the value of the variable "1" to the variable "2". As a result, it turns out that nothing changes, and the value of the variable "2" changes to the variable "1", that is, everything happens the other way around.
I don't know how to explain it clearly, so here's how I did it:
There is an object with "sessions", when the user sends a message, the following happens:
session[ID] = session[ID] || {
log: [PathTmpl.main_menu],
inline_log: '',
name: ctx.from.first_name,
last_name: ctx.from.last_name,
auth: 'new',
admin: false,
orders: [],
phone: '',
delivery: emptyAdress,
order: emptyOrder
}
const emptyOrder = {
id: 0,
name: '',
pack: '',
code: '',
amount: '',
price: ''
}
session[ID].order.code = code
…
session[ID].order.name = infoTxt.name
…
session[ID].order.pack = infoTxt.packing
…
session[ID].order.price = infoTxt.cost
…
session[ID].order.amount= amountNum
session[id].orders.push(session[id].order)
session[id].order = emptyOrder
console.log('\n session[id].orders : \n', session[id].orders) // массив
console.log('\n session[id].order : \n', session[id].order) // объект
console.log('\n emptyOrder : \n', emptyOrder) // константа
Answer the question
In order to leave comments, you need to log in
You are not assigning a value, but a reference to a value. This is the case with objects and arrays.
let a = {x:1};
let b = a; // Теперь a и b указывают на один и тот же участок памяти.
b.x = 2;
console.log(a.x); // 2 Ах, вот оно как!
//Как скопировать:
let c = {}; //Создается новый объект и под него выделяется новая память
c.x = a.x; //Копирование значений, т.к. x это не объект.
//Универсальный вариант (копируются все свойства):
a.y = 11;
a.z = 111;
let d = Object.assign({}, a);
console.log(d); // {x:1, y:11, z:111}
When you assign an object, you are assigning a reference to the object, not making a copy of it. And then you overwrite the fields of the emptyOrder itself, through a link to emptyOrder in session[ID].order. Need to make a copy of the data...
session[ID] = session[ID] || {
log: [PathTmpl.main_menu],
inline_log: '',
name: ctx.from.first_name,
last_name: ctx.from.last_name,
auth: 'new',
admin: false,
orders: [],
phone: '',
delivery: emptyAdress,
order: Object.assign({}, emptyOrder)
}
PS Don't forget to include a polyfill for Object.assign or use a similar framework method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question