Sample Code Analysis for copying JavaScript arrays and objects

Source: Internet
Author: User
This article describes how to copy JavaScript arrays and objects. It has good reference value. Next, let's take a look at it. This article mainly introduces the knowledge of JavaScript arrays and object replication. It has good reference value. Let's take a look at it with the small Editor.

I. Data Types

In a narrow sense, JavaScript divides all data into two types: basic type and reference type. The basic types include Undefined, Null, Boolean, Number, and String. The reference type is Object, commonly used arrays, dates, RegExp, and functions all belong to the Object type.

One of the differences between basic data and reference data is that when copying a variable, basic data copies a new copy independently, while reference data copies a reference of the original variable. The following is an example:

// Copy the basic data type var a = 10; var B = a; // B = 10a = 20; // a = 20, B = 10 // copy of referenced data var m = [1, 2]; var n = m; m [0] = 10; console. log (n [0]); // 10

If I want to copy the value of the reference type rather than the reference type, the above method is obviously not supported.

Ii. Shortest copying of Arrays

When an object (array) is copied, the value of the referenced field is not copied, but the reference of the corresponding field is copied. For example:

Var src = ['alpha', ['bravi', 'chalie ']; var dest = []; for (var I = 0; I <src. length; I ++) {dest [I] = src [I];} // if you change the reference field in src, the corresponding field in dest will also be changed to src [1]. push ('delta'); console. log (dest [1]); // ['braval', 'chalie', 'delta']

Shortest is generally used for one-dimensional arrays, that is, the array does not have a reference type. Common Methods for copying data are as follows:

Concat Method

 var src = ['alpha', 'bravo'],  dest = []; dest = dest.concat(src);

The concat method is more used in array merge, for example:

 var a = ['alpha', 'bravo'],  b = ['chalie', 'delta'],  combine; combine = a.concat(b);

In particular, concat is used for Array merging to copy all the elements in two (or more) arrays to the new object. For large arrays, the overhead is relatively large. A better way is to copy the elements of the last array to the previous array:

 var src = ['alpha', 'bravo'],  dest = ['chalie', 'delta']; Array.prototype.push.apply(src, dest);

Slice Method

The slice method can return the selected elements from an existing array and return a new array.

 var src = ['alpha', 'bravo'], var dest = src.slice(0);

3. Copying objects

The for-in traversal can be used for Object shortest replication. es6 provides a more convenient Object. assign () method.

 var src = {name: 'fox', age: 20},  dest = null; dest = Object.assign({}, src);

You can also use $. extend in jQuery and _. extend in underscore to copy objects.

Iv. Deep Replication

The application scenarios of shortest replication are limited. In more cases, we want to copy an object to a complete copy, this requires the typeof or instanof operator to judge the type of each field. If a field is of the basic type, you can copy it directly. If a field is of reference type, you need to make the above judgment on all fields of the field. This makes it easy for us to consider recursion to implement this function.

function deep_copy(src, dest) { for (var p in src) {  if (Array.isArray(src[p]) || src[p] instanceof Object) {   dest[p] = Array.isArray(src[p]) ? [] : {};   arguments.callee(dest[p], src[p]);  }else {   dest[p] = src[p];  } }}

In the above Code, arrays are special objects, so we can use for-in to traverse them.

You can also use the json Syntax:

 function deep_copy_in_json(src) {  return JSON.parse(JSON.stringify(src)); }

Although this is relatively simple, many attributes of the original object will be lost after the operation, such as the construtor attribute and some methods in the object prototype.

The above is the detailed analysis of code instances for copying JavaScript arrays and objects. For more information, see other related articles in the first PHP community!

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.