如何检查JSON响应元素是否为数组?

问题描述:

我收到下一个JSON回复

I am receiving the next JSON response

    {
    "timetables":[
        {"id":87,"content":"B","language":"English","code":"en"},                                                
        {"id":87,"content":"a","language":"Castellano","code":"es"}],
    "id":6,
    "address":"C/Maestro José"
    }

我想实现下一个伪代码功能

I would like to achieve the next pseudo code functionality

for(var i in json) {            
    if(json[i]  is Array) {
    // Iterate the array and do stuff
    } else {
    // Do another thing
    }
}

任何想法?

还有其他方法但据我所知,这是最可靠的方法:

There are other methods but, to my knowledge, this is the most reliable:

function isArray(what) {
    return Object.prototype.toString.call(what) === '[object Array]';
}

因此,要将其应用于您的代码:

So, to apply it to your code:

for(var i in json) {                    
    if(isArray(json[i])) {
    // Iterate the array and do stuff
    } else {
    // Do another thing
    }
}