The pits encountered when the for loop pushes an object to the array

The pits encountered when the for loop pushes an object to the array

The json array is assigned and pushed with a for loop, resulting in all the results printed are the same

As shown in the figure, the value of tree is
dynamically pushed into an array after the object is pushed into the result. The result of Console(this.tree[i].lable) is map1 map2 map3 map4 map9
The result of Console(this.tree) is map2 map2 map2 map2 map2

Because the Object object is passed by address reference, when the c object is declared outside the loop, the c added by a.push© is the same object every time. That is to say, a[0], a[1], and a[2] store the reference addresses of the same object. After modifying the properties of this object, all the places where the references of this object are stored will be affected.

Insert picture description here

Insert picture description here
Solution: Push the object in the loop, there is no problem of address reference.
Insert picture description here
Record this problem and
reprint it: https://bbs.csdn.net/topics/391988383?ops_request_misc=%25257B%252522request%25255Fid% 252522160929965016780273685996%%% 25253A 252522 252522 252522% 25252C% 252522scm%%% 25253A% 25252220140713.130102334.pc 25255Fall. 25257D% 252522% & 160929965016780273685996 & biz_id the request_id = = = & utm_medium distribute.pc_search_result.none-Task-2-discussion_topic All first_rank_v2 ~ rank_v29-1-391988383 .first_rank_v2_pc_rank_v29&utm_term=json%E6%95%B0%E7%BB%84%E7%94%A8for%E5%BE%AA%E7%8E%AF%E8%BF%9B%E8%A1%8C%E8%B5 %8B%E5%80%BC%E5%B9%B6push%EF%BC%8C%E5%AF%BC%E8%87%B4json%E6%89%80%E6%9C%89%E7%9A%84 %E6%95%B0%E6%8D%AE%E9%83%BD%E5%8F%98%E6%88%90%E4%B8%80%E6%A0%B7%E7%9A%84%E4 %BA%86%EF%BC%8C%E8%BF%99%E6%98%AF%E6%80%8E%E4%B9%88%E5%9B%9E%E4%BA%8B

Guess you like

Origin blog.csdn.net/weixin_40648700/article/details/111961160