Example of array reference in js

Source: Internet
Author: User

Array reference in js should be a basic knowledge:

Var arr = [1, 2, 3];
Var arr2 = arr;
Arr2 [0] = 5; // at this time, both arr and arr2 become [5, 2, 3]

How can we cut off such references? I know two methods:

1. Array slice method

Var arr = [1, 2, 3];
Var arr2 = arr. slice ();
Arr2 [0] = 5; // at this time, arr is [1, 2, 3] arr2 is [5, 2, 3] The slice method is equivalent to copying a new array.

2. concat method of array

Var arr = [1, 2, 3];
Var arr2 = arr. concat ();
Arr2 [0] = 5; // at this time, arr is [1, 2, 3]. arr2 is [5, 2, 3]. Like the slice method, the concat method is equivalent to copying a new array.

It is worth noting that the following problem is the function parameter passing method (this is the focus of this blog post)

Var a = [1, 2];
Var B = [5, 6];
Function change (x ){
X [0] = 3;
X = B;
X [1] = 9;
}
Change (a); // at this time, the value of a is [3, 2], not [5, 6], or [5, 9].

That is to say, the value of the array parameter can be modified in the function, but the array reference cannot be modified. After the array parameter reference is changed, the original array will not be affected, this is what you should pay attention to when using the reference relationship and function together.

Conclusion: js array is a reference type. It can only obtain or change the value reference type of the array through indexes, but cannot pass (it has assigned an external variable) the changed value is (the external variable assigned by it). The original array will not change.

Who can use pointers?

<Script type = "text/javascript" src = "/jquery. js"> </script>
<Script>
// Conclusion: Array-to-array is a reference type, and array-to-variable is a value type.
Var a = [1, 2, 4];
// Example 1
Var B =;
Alert (a); // 1234
Alert (B); // 1234
// Example 2
Var c =;
C [3] = 5;
Alert (c); // 1235
Alert (a); // 1235
// Example 3
Var d = a [1];
D = 10;
Alert (a); // 1234
</Script>
<Div id = "div"> </div

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.