判断一个变量是否为数组

(1)
var array = new Array("1", "2", "3", "4", "5"); 
console.log(array instanceof Array);//true
(2)
var array = new Array("1", "2", "3", "4", "5");
console.log(array.constructor ===Array);//true

(3)

function isArrayFn (o) { 
    return Object.prototype.toString.call(o) === '[object Array]'; 
} 
var arr = [1,2,3,1]; 
console.log(isArrayFn(arr));// true

call改变toString的this引用为待检测的对象,返回此对象的字符串表示,然后对比此字符串是否是'[object Array]',以判断其是否是Array的实例。

(4)

var arr = [1,2,3,1]; 
var arr2 = [{ abac : 1, abc : 2 }]; 
function isArrayFn(value){ 
    if (typeof Array.isArray === "function") { 
        return Array.isArray(value); 
    }else{ 
        return Object.prototype.toString.call(value) === "[object Array]"; 
    } 
} 
console.log(isArrayFn(arr));// true 
console.log(isArrayFn(arr2));// true
function isArrayFn (o) { 
    return Object.prototype.toString.call(o) === '[object Array]'; 
} 
var arr = [1,2,3,1]; 
console.log(isArrayFn(arr));// true

call改变toString的this引用为待检测的对象,返回此对象的字符串表示,然后对比此字符串是否是'[object Array]',以判断其是否是Array的实例。

(4)

var arr = [1,2,3,1]; 
var arr2 = [{ abac : 1, abc : 2 }]; 
function isArrayFn(value){ 
    if (typeof Array.isArray === "function") { 
        return Array.isArray(value); 
    }else{ 
        return Object.prototype.toString.call(value) === "[object Array]"; 
    } 
} 
console.log(isArrayFn(arr));// true 
console.log(isArrayFn(arr2));// true
posted @ 2017-05-01 14:12  安静的嘶吼  阅读(268)  评论(0编辑  收藏  举报