方法一:Array.isArray()
- Array.isArray() 用于确定传递的值是否是一个 Array;返回 boolean 型,如果值是 Array则为 true;否则为 false
// 下面的函数调用都返回 true
Array.isArray([])
Array.isArray(new Array())
// 鲜为人知的事实:其实 Array.prototype 也是一个数组,会打印出原型链上的所有方法
Array.isArray(Array.prototype)
方法二:instanceof 运算符
- 判断一个变量是否是数组的实例对象,如果变量是 Array 的实例对象,则为 true; 否则为 false
- 当检测 Array 实例时,Array.isArray 优于 instanceof,因为 Array.isArray 能检测 iframes
var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
xArray = window.frames[window.frames.length-1].Array
var arr = new xArray(1,2,3) // [1,2,3]
Array.isArray(arr) // true
arr instanceof Array // false
方法三:Object.prototype.toString.call()
- Object.prototype.toString.call() 方法判断一个变量数据类型,返回字符串数组,如 '[object Object]'
- 假如不存在 Array.isArray() 方法,封装以下函数
function isArray(arr){
return Object.prototype.toString.call(arr) === '[object Array]'
}
const res = isArray([])
console.log(res)
参考资料: