js的数组和对象的多种复制和清空, 以及区分JS数组和对象的方法

js的数组和对象的多种”复制”和”清空”, 以及区分JS数组和对象的方法
一.数组清空与复制方法
1.数组清空的方法
var a = [1,2,3];
a.length = 0; //方法1
a.splice(0, a.length); //方法2

2.数组复制方法
var a = [1,2,3];
a.slice(0)

二.对象清空与复制方法
1.判断对象是否为空
Object.key.length==0 //为空 ES6

2.对象复制
(1).万能办法
function clone(obj){
let temp = null;
if(obj instanceof Array){
temp = obj.concat();
}else if(obj instanceof Function){
//函数是共享的是无所谓的,js也没有什么办法可以在定义后再修改函数内容
temp = obj;
}else{
temp = new Object();
for(let item in obj){
let val = obj[item];
temp[item] = typeof val == ‘object’?clone(val):val; //这里也没有判断是否为函数,因为对于函数,我们将它和一般值一样处理
}
}
return temp;
}

(2).JSON对象序列化方法, 弊端: 不能复制函数
JSON.parse(JSON.stringify(obj))

三.判断是否为数组和对象的方法
1.toString方法
Object.prototype.toString.call(array) === ‘[object Array]’ //true
Object.prototype.toString.call(obj) === ‘[Object Object]’ //true

2.constructor方法
obj.constructor === Array//true
obj.constructor === Object //true

3.instanceof方法, 弊端: 区分不开对象或者数组
obj instaceof Object //true
array instaceof Object// true

4.isArray方法
Array.isArray([1,2,3]) //true

以上是我认为无懈可击的方法, 其他还有很多, 需要请留言想了解原生js的”数组”和”对象”的方法, 请点击 JavaScript教程-阮一峰

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理