JS - 数据类型的值拷贝函数(深拷贝)
程序员文章站
2022-04-22 18:29:38
...
function mottoClone (obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Boolean) return new Boolean(obj.valueOf());
if (obj instanceof Number) return new Number(obj.valueOf());
if (obj instanceof String) return new String(obj.valueOf());
if (obj instanceof RegExp) return new RegExp(obj.valueOf());
if (obj instanceof Date) return new Date(obj.valueOf());
var cpObj = obj instanceof Array ? [] : {};
for (var key in obj) cpObj[key] = myClone(obj[key]);
return cpObj;
}
支持的数据类型或格式有:Boolean,Number,String,RegExp,Date,Function,Array,JSON
支持深拷贝(循环迭代),如:
var obj = {
id: 1,
name: 'xxx',
sayName: function () {
console.log('my name is' + this.name);
},
childs: [
{},
{},
...
],
opts: {
xxx: [],
...
},
...
};
var newObj = mottoClone(obj);
以上就是JS - 数据类型的值拷贝函数(深拷贝)的详细内容,更多请关注其它相关文章!
上一篇: charles抓取eclipse中的请求
下一篇: linux下安装sql server