js中判断一个变量是数组的方式有哪些
常用的方式有以下4种:
- Array.isArray(list);
- list instanceof Array;
- Object.prototype.toString.call(list) === “[object Array]”
- 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");
}