Home Web Front-end JS Tutorial Detailed explanation of clone object in javascript

Detailed explanation of clone object in javascript

May 16, 2016 pm 04:29 PM
javascript

This article mainly introduces the method of cloning objects in javascript. Friends in need can refer to it.

During development, it is common to interrupt the reference relationship between objects and just want to make a copy. Clone an object is inevitable.

In JavaScript, the simple method is to use the JSON function to stringify the object into a string, and then parse it into a new object. Or just search for code from the Internet. There are still a lot of clone codes in the open source community.

Although the code can be found, things will always belong to others, and learning to code by hand will always be a constant theme.

I wrote two clone functions myself:

cloneOwn: Clone the own properties of the custom object, excluding inherited properties. The properties can be basic data types and arrays, customized Object, you can specify a list of attribute names to be cloned.

cloneArray: Clone an array. The elements in the array can be objects or basic types.

//第一个参数是被克隆的对象,第二个参数是需要克隆的属性列表
function cloneOwn() {
  var obj = arguments[0];
  if (typeof obj === 'undefined' || obj === null)
      return {};
  if (typeof obj !== 'object')
      return obj;
  //第二个参数是属性名称列表,就采用该列表进行刷选
  //否则就克隆所有属性
  var attrs = arguments[1];
  var enable_spec_attr = true;
  if (!(attrs instanceof Array)) {
      //console.log(attrs);
      attrs = obj;
      enable_spec_attr = false;
  }
  var result = {};
  var i;
  for (i in attrs) {
      attr = enable_spec_attr? attrs[i]: i;
      //console.log(attr);
      if (obj.hasOwnProperty(attr)) {
          if (obj[attr] instanceof Array) {
              result[attr] = cloneArray(obj[attr]);
          }
          else if (typeof obj[attr] === 'object') {
              result[attr] = cloneOwn(obj[attr]);
          } else {
              result[attr] = obj[attr];
          }
      }
  }
  return result;
}
Copy after login
//克隆数组
function cloneArray(array) {
  if (typeof array === 'undefined' || array === null)
    return [];

  if (!(array instanceof Array))
    return [];
  result = [];
  var i;
  for(i in array) {
    if (typeof array[i] !== 'object') {
      result[i] = array[i];
      continue;
    }
    //clone object
    result[i] = cloneOwn(array[i]);
  }
  return result;
}
Copy after login

Call

1. Regularly clone the custom object:

var a = {
  name:'frank',
  age:20
};
var b= cloneOwn(a);
Copy after login

2. Specify the attributes of the clone

var a = {
    name:'frank',
    age:20,
    address:'any where'
};
var b = cloneOwne(a, ['name', 'age']);
Copy after login

3. Clone a custom object that contains array attributes

var a = {
    name: 'kxh',
    age: 20,
    books: ['hai','ho','ali'],
    likes: [
        {wname: 'kaili', wage: 81, fav: "aaaaa"},
        {wname: 'seli', wage: 82, fav: "bbb"},
        {wname: 'ailun', wage: 83, fav: "ccc"},]
};
var b = cloneOwne(a);
Copy after login

4. Clone an array that contains a custom object

var a = [
   {
      name:'frank',
      age:20
    },
    {
       name:'leon',
       age:30
     }
];
var b = cloneArray(a);
Copy after login

The above code still has many problems, such as , there are some problems with the cloning of built-in objects, such as datatime type.

Problem management is a learning process.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to implement an online speech recognition system using WebSocket and JavaScript

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to implement an online reservation system using WebSocket and JavaScript

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

How to use JavaScript and WebSocket to implement a real-time online ordering system

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecasting system

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

Simple JavaScript Tutorial: How to Get HTTP Status Code

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

How to get HTTP status code in JavaScript the easy way

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

How to use insertBefore in javascript

See all articles