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

8次阅读

共计 965 个字符,预计需要花费 3 分钟才能阅读完成。

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 教程 - 阮一峰

正文完
 0