Javascript Object Reference Note

Source: Internet
Author: User

When using forEach and other statements in js to form a loop class, the outer object is referenced, and the loop body is constantly assigned an attribute to this object, the final operation is the final value of this attribute after the loop. Eg: copy the code var testObj = {"a": 1, "B": 2}, testArr = [1, 2, 4, 5], newArr = []; testArr. forEach (function (index) {testObj. c = index; newArr. push (testObj) ;}); console. log (newArr); copy the code. The main problem here is the object reference. Beginners may think that each of the available C files is different. In fact, all the objects pushed in newArr are testObj objects, this object is always defined outside, and testObj in newArr will all be the same value, and c will be the final value of the loop. For detailed analysis, see js advanced program design. The solution includes the object cloning solution and the related depth copy solution, the main idea is to clone the object to get a new object that can be modified. The first method is to clone the object before and after the object reference is no longer the same: var cloneObj = function (obj) {if (obj) {return JSON. parse (JSON. stringify (obj);} return obj;} the second method is the shallow copy of the object. The Copied object is the same as the reference of the property of the Copied object, the newly added attributes are different references: copy the code var copyObj = function (obj) {var newObj ={}; for (var I in obj) {if (obj. hasOwnProperty (I) {newObj [I] = obj [I] ;}} return newObj ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.