简体   繁体   中英

Checking if object is Array in Parse.com CloudCode

I have this code running on Parse.com CloudCode

queryContact.find().then(function(results) {

    console.log(typeof results); // object

    if (results.constructor !== Array) {

        response.success("Found zero results");

    } else {

        console.log("WHY DID IT GO THROUGH!!!");
    }

}).then...

The find() function normally returns an array, but in my test case it returns 0 results. By logging to console I managed to see that in this case results is a typeof object . I want to proceed with else case only if results is typeof Array . However, my checks fail to capture this, and the code keeps falling through into the else section. None of the checks from this SO question work for me.

I ended up using

if (results.length === 0) {

Somehow this just worked for me.

检查对象是否为数组

 Object.prototype.toString.call(results) === '[object Array]'

Try this.

 if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
   alert( 'Array!' );
 }else{
   alert( 'object!' );
 }

You can use the following to return the names of JavaScript types:

function toType(x) {
  return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

toType([]); // array
toType({}); // object

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM