Home > Article > Web Front-end > Detailed explanation of clone object/function code in javascript
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.
Wrote two cloning functions:
cloneOwn: Clone the own properties of a custom object, excluding inherited properties. Properties can be basic data types and arrays, custom objects , you can formulate 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; }
//克隆数组 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; }
Call
1. Regular clone custom object:
var a = { name:'frank', age:20 }; var b= cloneOwn(a);
2. Specify the attributes of the clone
var a = { name:'frank', age:20, address:'any where' }; var b = cloneOwne(a, ['name', 'age']);
3. Clone contains array attributes Custom object
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);
4. Clone array containing custom object
var a = [ { name:'frank', age:20 }, { name:'leon', age:30 } ]; var b = cloneArray(a);
The above is the detailed content of Detailed explanation of clone object/function code in javascript. For more information, please follow other related articles on the PHP Chinese website!