Initial study of JavaScript value types and reference types

Source: Internet
Author: User

Today encountered a pit, specifically not much to say, directly on the code

 var a = [[],[],[1,2,3]]var b = [' Color ', ' size ', ' size ']var arr = []fo R(Let i = 0; i < a.length; i + +)    {= {    }for (Let j = 0; J < A[i].length; j + +)        {= a[i][j]        arr.push (obj)        console.log (arr)        console.log (obj)    }} Console.log (arr)

I expect the result of ARR should be

[{' Size ': 1}, {' Size ': 2}, {' Size ': 3}]

Finally arr's the result is this

[{' Size ': 3}, {' Size ': 3}, {' Size ': 3}]

Ask in a group of friends and finally come to your own conclusion-this is because of the different value types and reference types.

The values in JavaScript are roughly divided into two types, one value type and one reference type.

Value types: Numeric, Boolean, null, undefined

Reference types: objects, arrays, functions

The obj in our example is different each time it is printed, but because it is a reference type, arr is also a reference type, even if obj is push into arr, it just push into a memory address, so the last obj becomes 3, and the obj referenced in arr will all become 3. It's amazing, and the final solution is simple.

 var a = [[],[],[1,2,3]]var b = [' Color ', ' size ', ' size ']var arr = []fo R(Let i = 0; i < a.length; i + +)    {for (let j = 0; J < A[i].length; J + +) {     = {}        = A[i][j]        arr.push (obj)    }}console.log (arr)

As long as the declaration of obj is placed inside the innermost loop, each loop will be a separate memory address, so that the last obj, even if it becomes 3, will not be affected by the previous obj because their memory address has different roots.

Initial study of JavaScript value types and reference types

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.