JS基础回顾,小练习(克隆对象,数组)

对象的克隆:

var srcObj = {
a: 1,
b: {
b1: ["hello", "hi"],
b2: "JavaScript"
}
}; function cloneObject(src) {
var target = {};
for(var k in src){
target[k] = src[k];
}
return target;
}
var o = cloneObject(srcObj);
console.log(o===srcObj); //false

数组的克隆:

方法1:

var srcArr = ['html','css','javascript','Jquery','ajax','less'];
function cloneArr(src) {
var target = [];
for(var i=0;i<src.length;i++){
target[i] = src[i];
}
return target;
}
var arr = cloneArr(srcArr);
console.log(arr);
console.log(arr===srcArr); //false

方法2:

var srcArr = ['html','css','javascript','Jquery','ajax','less'];
function cloneArr(src) {
return srcArr.join().split(",");
}
var arr = cloneArr(srcArr);
console.log(arr);
console.log(arr===srcArr); //false

方法3:

var srcArr = ['html','css','javascript','Jquery','ajax','less'];
function cloneArr(src) {
var arr = [];
for(var k in src){
arr[k] = src[k];
}
return arr;
}
var arr = cloneArr(srcArr);
console.log(arr);
console.log(arr===srcArr); //false

方法4:

var srcArr = ['html','css','javascript','Jquery','ajax','less'];
function cloneArr(src) {
var len = src.length,arr=[];
var str = src.toString();
var reg = /([\d\w]+),/g;
var i = 0,m;
while(m = reg.exec(str)){
arr[i] = m[1];
i++;
}
return arr;
}
var arr = cloneArr(srcArr);
console.log(arr);
console.log(arr===srcArr); //false
上一篇:javascript原型prototype浅识


下一篇:ASP.NET 数据库访问通用工具