js中判断一个变量是数组的方式有哪些

常用的方式有以下4种:

  1. Array.isArray(list);
  2. list instanceof Array;
  3. Object.prototype.toString.call(list) === “[object Array]”
  4. list.constructor === Array

注:list是要判断的变量。

let list = [1,2,3]
// 判断list是否是个数组
if (Array.isArray(list)) {
    
    
    console.log("It's an array");
} else {
    
    
    console.log("It's not an array");
}
// 再换个方式判断list是否是个数组
if (list instanceof Array) {
    
    
    console.log("It's an array");
} else {
    
    
    console.log("It's not an array");
}

// 再换个方式判断list是否是个数组
if (Object.prototype.toString.call(list) === "[object Array]") {
    
    
    console.log("It's an array");
} else {
    
    
    console.log("It's not an array");
}
// 再换个方式判断list是否是个数组
if (list.constructor === Array) {
    
    
    console.log("It's an array");
} else {
    
    
    console.log("It's not an array");
}

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/134625685