您的位置:首页 > Web前端 > JavaScript

【学习笔记一】- JS 类型识别 和 deepclone 深复制

2017-08-25 00:04 549 查看
写在前面:

本人自学前端不久,博客的【学习笔记】既不算原创也不算转载,都是自己通过各个网站、博客、书籍、视频课程等学习的笔记,以及做的一些测试。

下面的代码是在sublime text3上编辑在nodejs上运行过的。

/**js类型识别的四种方法:
*
* 1.typeof
* typeof可识别标准类型,但不能识别Null,不能识别除Function之外的具体对象类型
* 识别String、Number、Boolean、Undefined、Object、Function类型
*/
console.log(typeof []);//object
/**
* 2.Object.prototype.toString
* 可以识别标准类型:
* String、Number、Boolean、Undefined、Object、Null;
* 可以识别内置对象类型:
* Object、String、Number、Boolean、Function、Array、Date、RegExp、Error、Math、JSON、全局对象
* 不能识别自定义对象类型
*/
function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
//call方法让obj使用Object.prototype.toString方法,
//返回例如"object Number"
}
console.log(type(global));//global
/**
* 3.constructor
* 识别标准类型除Null、Undefined(它们无构造器)
* 识别内置对象类型
* 识别自定义对象类型
*/
console.log('123'.constructor);//[Function: String]
var a=123;
console.log(a.constructor);//[Function: Number]
console.log([].constructor==Array);//true
function Person(name){
this.name=name;
}
console.log(new Person('ccc').constructor);//[Function: Person]
console.log(Person.constructor);//[Function: Function]
//获取最想构造函数名称
function getConstructorName(obj){
return obj&&obj.constructor&&obj.constructor.toString().match(/function\s*([^(]*)/)[1];
}
console.log(getConstructorName([]));
/**
* 4.instanceof
* 识别内置对象类型
* 能识别自定义对象类型
*
* 不能识别原始类型:
* String、Number、Boolean、Undefined、Null;
*/
console.log([] instanceof Array);//true
console.log('a' instanceof String);//false
console.log('---------------------------------------------------');

/*function fun(obj) {
    var obj = obj || {};
//if(obj === 0 || obj === "" || obj === false || obj === null || obj === undefined){obj = {};}
//即,data不存在时obj为{}
}*/
//一维数组的深拷贝方法:slice、concat
/**
arrayObj.slice(start, end)
只有一个参数时从该位置一直复制到结尾
不改变原数组
if(start<0)
start+=length;
if(end<0)
end+=length;
if(end<start)
不复制
*/

var array = ["One","Two","Three"];
var copyarray = array.slice();
copyarray[1] = "replace sth";
console.log(array);
//Export:[ 'One', 'Two', 'Three' ]
console.log(copyarray);
//Export:[ 'One', 'replace sth', 'Three' ]
console.log('---------------------------------------------------');
var array = ["One",["One","Two","Three"],"Three"];
var copyarray = array.slice();
copyarray[1][1]="replace sth";
console.log( array);
//Export:[ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ]
console.log(copyarray);
//Export:[ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ]
console.log('---------------------------------------------------');
/**
* concat() 方法用于连接两个或多个数组,该方法不会改变现有的数组.
*/
var array = ["One","Two","Three"];
var copyarray = array.concat();
copyarray[1] = "replace sth";
console.log( array);
//Export:[ 'One', 'Two', 'Three' ]
console.log(copyarray);
//Export:[ 'One', 'replace sth', 'Three' ]
console.log('---------------------------------------------------');
var array = ["One",["One","Two","Three"],"Three"];
var copyarray = array.concat();
copyarray[1][1]="replace sth";
console.log( array);
//Export:[ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ]
console.log(copyarray);
//Export:[ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ]
console.log('---------------------------------------------------');
function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
function deepclone(data){
var clone;
if(type(data)==='array'){
clone=[];
for (var i = 0; i < data.length; i++) {
clone[i]=deepclone(data[i]);
}
}else if(type(data)==='object'){
clone={};
for (var key in data) {
clone[key]=deepclone(data[key]);
}
}else{
clone=data;
}
return clone;
}

//测试
var a='a';
var b=deepclone(a);
console.log(a);//a
console.log(b);//a
a='b';
console.log(a);//b
console.log(b);//a
console.log('---------------------------------------------------');

var array = ["One",["One","Two","Three"],"Three"];
var copyarray = deepclone(array);
console.log(array);//[ 'One', [ 'One', 'Two', 'Three' ], 'Three' ]
console.log(copyarray);//[ 'One', [ 'One', 'Two', 'Three' ], 'Three' ]
copyarray[1][1]="replace sth";
console.log(array);//[ 'One', [ 'One', 'Two', 'Three' ], 'Three' ]
console.log(copyarray);//[ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ]
console.log('---------------------------------------------------');

var obj={a:1,b:'abc',c:true,d:["One",["One","Two","Three"],"Three"],e:{key:1,keykey:'string'}};
var copyobj=deepclone(obj);
console.log(obj);
/*{ a: 1,
b: 'abc',
c: true,
d: [ 'One', [ 'One', 'Two', 'Three' ], 'Three' ],
e: { key: 1, keykey: 'string' } }*/
console.log(copyobj);
/*{ a: 1,
b: 'abc',
c: true,
d: [ 'One', [ 'One', 'Two', 'Three' ], 'Three' ],
e: { key: 1, keykey: 'string' } }*/
obj.d[1][1]="replace sth";
console.log(obj);
/*{ a: 1,
b: 'abc',
c: true,
d: [ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ],
e: { key: 1, keykey: 'string' } }*/
console.log(copyobj);
/*{ a: 1,
b: 'abc',
c: true,
d: [ 'One', [ 'One', 'Two', 'Three' ], 'Three' ],
e: { key: 1, keykey: 'string' } }*/
/**
* 借助JSON全局对象
* var newobj = JSON.parse(JSON.stringify(obj));
* 深复制后构造函数变成Object
*/
var arr=["One",["One","Two","Three"],"Three"];
var newobj = JSON.parse(JSON.stringify(arr));
console.log(newobj.constructor);//[Function: Array]
console.log(arr.constructor);//[Function: Array]
newobj[1][1]='replace sth';
console.log(arr);//[ 'One', [ 'One', 'Two', 'Three' ], 'Three' ]
console.log(newobj);//[ 'One', [ 'One', 'replace sth', 'Three' ], 'Three' ]
console.log('---------------------------------------------------');
/**借助框架实现深复制
* 1.Underscore —— _.clone()
*
* 2.jQuery —— $.extend()
* 深复制 JSON 对象
* var newobj=$.extend(true, {}, obj);
* 	<script type="text/javascript">
var obj = {
a: 'a string',
b: { obj2: { key: 1 } },
c: [ 0 ,[10,11,12] , 2 ]
};

var shallow = $.extend({}, obj),
deep = $.extend(true, {}, obj);

if(shallow.b.obj2=== obj.b.obj2){document.write('shallow'); }
if(deep.c[1] === obj.c[1]){document.write('deep'); }
//shallow
</script>
*
* 3.lodash —— _.clone() / _.cloneDeep()
* _.clone(obj, true)等价于_.cloneDeep(obj)
* var newobj = _.cloneDeep(obj);
*/





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息