久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

JS對象復制(深拷貝和淺拷貝)

瀏覽:97日期:2024-03-30 17:08:46
一、淺拷貝1、Object.assign(target,source,source...)

a、可支持多個對象復制

b、如果source和target屬性相同 source會復制target的屬性

c、target只能為Object對象

var obj = {a:1,b:2}undefinedObject.assign({c:3},obj){c: 3, a: 1, b: 2}obj{a: 1, b: 2} 兼容性寫法if(Object.assign){//兼容}else{//不兼容}2、擴展運算符(spread)

支持將多個對象復制到一個對象上“

var obj1 = { foo: 'foo' };var obj2 = { bar: 'bar' }; var copySpread = { ...obj1, ...obj2 }; // Object {foo: 'foo', bar: 'bar'}copySpread {foo: 'foo', bar: 'bar'}var obj = {a:1,b:2,c:3}var objs = {...obj}objs{a: 1, b: 2, c: 3}objs.a=1010objs{a: 10, b: 2, c: 3}obj{a: 1, b: 2, c: 3}二、深拷貝1、使用對象序列化 JSON.stringify()和JSON.parse()

注意:此方法僅在原對象包含可序列化值類型且沒有任何循環(huán)引用時才有效。不可序列化值類型的一個例子是Date對象 -JSON.parse只能將其解析為字符串而無法解析回其原始的Date對象 或者對象中屬性值為function

var obj = {a:1,b:[1,2,3],c:{e:3},bool:false}undefinedvar objs = JSON.parse(JSON.stringify(obj))undefinedobjs{a: 1, b: Array(3), c: {…}, bool: false}objs.bool = truetrueobjs{a: 1, b: Array(3), c: {…}, bool: true}obj{a: 1, b: Array(3), c: {…}, bool: false}2、使用遞歸,對對象屬性進行判斷

function deepClone(obj) { var copy; // 如果 obj 是 null、undefined 或 不是對象,直接返回 obj // Handle the 3 simple types, and null or undefined if (null == obj || 'object' != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) {copy[i] = clone(obj[i]); } return copy; } // Handle Function if (obj instanceof Function) { copy = function() { return obj.apply(this, arguments); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error('Unable to copy obj as type isn’t supported ' + obj.constructor.name);}

以上就是JS對象復制(深拷貝和淺拷貝)的詳細內(nèi)容,更多關于JS的資料請關注好吧啦網(wǎng)其它相關文章!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 镇坪县| 南京市| 永登县| 河源市| 张家口市| 大新县| 九寨沟县| 巫溪县| 佛学| 南开区| 剑川县| 巨野县| 栖霞市| 股票| 大冶市| 翼城县| 饶平县| 沐川县| 嘉善县| 高邑县| 涡阳县| 五指山市| 淳化县| 安图县| 巫山县| 静宁县| 美姑县| 贡觉县| 喀喇| 鹿泉市| 工布江达县| 昌邑市| 安徽省| 井冈山市| 桃江县| 舟山市| 卢龙县| 云阳县| 大化| 安西县| 梅河口市|