You have only one ProdStruct
object, which you're referring to seven times. That is, you have something like this in memory:
+??????????????+
ProdStruct??????????????+?+?+?+?+?+?+??>| (object) |
/ / / / / / / +??????????????+
| | | | | | | | price: 0 |
| | | | | | | | available: 0 |
| | | | | | | +??????????????+
+??????????+ | | | | | | |
Prods???>| (object) | | | | | | | |
+??????????+ | | | | | | |
| 1 |??+ | | | | | |
| 2 |????+ | | | | |
| 3 |??????+ | | | |
| 4 |????????+ | | |
| 5 |??????????+ | |
| 6 |????????????+ |
| 7 |??????????????+
+??????????+
Modifying the state of that one object (changing price
) modifies its state; doesn't matter which of the seven references you use to get to it to make the change or to look at the result, it's just one object.
You'd need to make a copy of the object to get the result you expect. One way is to use Object.assign
:
var ProdStruct = {
'price' : 0,
'available' : 0,
};
var Prods = {
'1' : Object.assign({}, ProdStruct),
'2' : Object.assign({}, ProdStruct),
'3' : Object.assign({}, ProdStruct),
'4' : Object.assign({}, ProdStruct),
'5' : Object.assign({}, ProdStruct),
'6' : Object.assign({}, ProdStruct),
'6' : Object.assign({}, ProdStruct),
'7' : Object.assign({}, ProdStruct)
};
Prods['6']['price'] = 99;
console.log(Prods);
.as-console-wrapper {
max-height: 100% !important;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…