js的數組和對象的多種"複製"和"清空", 以及區分JS數組和對象的方法

js的數組和對象的多種"複製"和"清空", 以及區分JS數組和對象的方法

一.數組清空與複製方法

1.數組清空的方法javascript

var a = [1,2,3];    
a.length = 0;           //方法1 
a.splice(0, a.length);  //方法2

2.數組複製方法html

var a = [1,2,3];
a.slice(0)

二.對象清空與複製方法

1.判斷對象是否爲空java

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對象序列化方法, 弊端: 不能複製函數prototype

JSON.parse(JSON.stringify(obj))

三.判斷是否爲數組和對象的方法

1.toString方法code

Object.prototype.toString.call(array) === '[object Array]'  //true
Object.prototype.toString.call(obj) === '[Object Object]'  //true

數值:返回[object Number]。 
字符串:返回[object String]。 
布爾值:返回[object Boolean]。
undefined:返回[object Undefined]。 
null:返回[object Null]。 
數組:返回[object Array]。 
arguments 對象:返回[object Arguments]。 
函數:返回[object Function]。
Error 對象:返回[object Error]。 
Date 對象:返回[object Date]。 
RegExp 對象:返回[object RegExp]。 
其餘對象:返回[object Object]。

2.constructor方法htm

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

相關文章
相關標籤/搜索