如何判断一个对象是否为数组-多种方式

1.Object.prototype.toString.call()

function isArray(obj) {
     
        if (typeof obj === 'object'){
     
            return Object.prototype.toString.call(obj) === '[object Array]';
        }
        return false;
    }

测试:

	let arr = [1,2,3];
    let num = 520;
    let res = isArray(arr);
    let res2 = isArray(num);
    console.log(res);//true
    console.log(res2);//false

2.Array.isArray

 	let arr = [1,2,3];
    let num = 520;
    let res = Array.isArray(arr);
    let res1 = Array.isArray(num);
    console.log(res);//true
    console.log(res1);//false

3.判断原型对象是不是Array的原型对象

	let arr = [1,2,3];
    let obj = {
     num:520};
    console.log(arr.__proto__ === Array.prototype);//true
    console.log(obj.__proto__ === Array.prototype);//false

4.instanceof

	let arr = [1,2,3];
    let obj = {
     num:520};
    console.log(arr instanceof Array);//true
    console.log(obj instanceof Array);//false

5.xxx.constructor.name

    	let arr = [1,2,3];
        let obj = {
     num:520};
        console.log(arr.constructor.name);//Array
        function isArray(obj) {
     
            if (typeof obj === 'object'){
     
                return obj.constructor.name === 'Array';
            }
            return false;
        }
        let res = isArray(arr);
        let res1 = isArray(obj);
        console.log(res);//true
        console.log(res1);//false

6.Array.prototype.isPrototypeOf(arr)

let arr = [1,2,3];
console.log(Array.prototype.isPrototypeOf(arr));//true

你可能感兴趣的:(js基础,js基础,常见面试题)