Javascript 如何识别给定的响应是object、array还是null。如果这三种类型均为';对象';
如果我们得到响应数据,我想检查给定的响应数据是object、Array还是null。这三种类型相同,那么如何识别给定的响应是数组、对象还是null。让我们假设我们有一个varJavascript 如何识别给定的响应是object、array还是null。如果这三种类型均为';对象';,javascript,Javascript,如果我们得到响应数据,我想检查给定的响应数据是object、Array还是null。这三种类型相同,那么如何识别给定的响应是数组、对象还是null。让我们假设我们有一个varfoo,它可以是这三种类型中的任何一种。我们可以这样做: if (foo === null) { } else if (Array.isArray(foo)) { } else if (typeof foo === 'object') { // this may include dates and other types
foo
,它可以是这三种类型中的任何一种。我们可以这样做:
if (foo === null) {
} else if (Array.isArray(foo)) {
} else if (typeof foo === 'object') { // this may include dates and other types, classified as 'object'
}
只需使用
instanceof
检查数据类型即可
就你而言:
if (response instanceof Array || response instanceof Object || response === null) {
//The variable 'response' is one of these types.
}
查看文档。如果为空,请与空进行比较<代码>数据===null?数组有长度属性,而对象没有。因此,您可以检查:.hasOwnProperty(长度)。如果为true,则为数组;如果为false,则为对象。