在JavaScript中,如何检测天气的类型是数组或对象

In JavaScript how to detect weather the type is Array or Object?

本文关键字:类型 对象 数组 检测 JavaScript 何检测      更新时间:2023-09-26

我需要知道如何检查变量是数组还是对象

var arr = ['foo', 'bar'];
var obj = {
  0: 'foo',
  1: 'bar'
}
document.write('arr is an: ' + typeof arr + ', obj is an: ' + typeof obj)
// The result is always:
// arr is an: object, obj is an: object

有没有办法区分这两种类型?

Array.isArray(arr)将返回trueArray.isArray(obj)会返回false.