当前位置:Gxlcms > JavaScript > JS-数据类型的值拷贝函数(深拷贝)

JS-数据类型的值拷贝函数(深拷贝)

时间:2021-07-01 10:21:17 帮助过:51人阅读

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 - 数据类型的值拷贝函数(深拷贝)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行