感覺(jué)這個(gè)題目涉及的基礎(chǔ)知識(shí)內(nèi)容比較多,故分享出來(lái),后面會(huì)詳細(xì)介紹數(shù)據(jù)類(lèi)型的文章,歡迎關(guān)注。
實(shí)現(xiàn)一個(gè)函數(shù)clone,可以對(duì)JavaScript中的5種主要的數(shù)據(jù)類(lèi)型(包括Number、String、Object、Array、Boolean)進(jìn)行值復(fù)制。
/**
* 對(duì)象克隆
* 支持基本數(shù)據(jù)類(lèi)型及對(duì)象
* 遞歸方法
*/
function clone(obj) {
var o;
switch (typeof obj) {
case "undefined":
break;
case "string":
o = obj + "";
break;
case "number":
o = obj - 0;
break;
case "boolean":
o = obj;
break;
case "object": // object 分為兩種情況 對(duì)象(Object)或數(shù)組(Array)
if (obj === null) {
o = null;
} else {
if (Object.prototype.toString.call(obj).slice(8, -1) === "Array") {
o = [];
for (var i = 0; i obj.length; i++) {
o.push(clone(obj[i]));
}
} else {
o = {};
for (var k in obj) {
o[k] = clone(obj[k]);
}
}
}
break;
default:
o = obj;
break;
}
return o;
}
如果你有高級(jí)前端的水平,這個(gè)時(shí)候就應(yīng)該寫(xiě)出下面的代碼
Object.prototype.clone = function(){
var o = this.constructor === Array ? [] : {};
for(var e in this){
o[e] = typeof this[e] === "object" ? this[e].clone() : this[e];
}
return o;
}
基礎(chǔ)知識(shí)還需要牢固,要不怎么能寫(xiě)出這樣高端的寫(xiě)法呢?哈哈??