我正在运行一个 AJAX
请求,它返回一个 JSON
格式的响应,如下所示:
{
name: "gideon",
class: "knight",
...
}
或
[
{
name: "gideon",
class: "knight",
...
},
{
name: "athena",
class: "mage",
...
},
...
{
name: "chris",
class: "B.O.W Agent",
....
}
]
现在,我如何知道调用的返回类型是 Object
还是对象的 Array
?我需要对此进行检查(加上其他检查):
$.ajax({
...,
success: function(r) {
if(/* r is an object */) {
}
else if(/* r is an array */) {
// Perform an iteration
}
}
});
我已经针对 Object
对这两个返回值执行了 instanceof
和 typeof
运算符,但这当然很愚蠢,因为 Array
是 Object
的后代,因此它总是返回true
。
最佳答案
使用Array.isArray()喜欢
$.ajax({
...,
success: function(r) {
if(Array.isArray(r)) {
// Perform an iteration
}
else if(/* r is an object */) {
}
}
});
关于javascript - Javascript 中数组与对象数据类型的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30992997/