简体   繁体   中英

Check if an Obj is Empty Array

Is there some native/lodash/underscore/etc method to check if an obj is an empty array? [] === [] returns false due to different obj references. I wrote a quick checker for it:

  function isArrayOfLength(obj, length) {
    var isArrayOfSpecifiedLength = false; 

    if(Array.isArray(obj)){ 
      if(obj.length === length){
        isArrayOfSpecifiedLength = true; 
      }
    }

    return isArrayOfSpecifiedLength; 
  } 

but I don't want to clutter up production code if something better is available. Plunk if you want it for whatever reason . Note - I need to be able to check any var type - the method might get an obj or an int, so I can't just check length without verifying that it's an array.

It's super-simple:

function isEmptyArray(obj) {
   return Array.isArray(obj) && obj.length === 0;
}

Try this

var ap = (Array.isArray(obj) && (obj.length === 0))? true : false;

if ap evaluates to true then you will know its an empty array

With Ramda you can use R.isArrayLike([]); //=> true R.isArrayLike([]); //=> true to check if it's an array, and R.isEmpty([]); //=> true R.isEmpty([]); //=> true to verify if has data.

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