Вопрос

I want to check the response.data.totalRows is empty.

if (response!=undefined
   && response.data!=undefined
   && response.data.totalRows!=undefined) {

  alert(response.data.totalRows);
}

Can simplify the code?

UPDATE: it seems that there is no simple method like isEmpty(response.data.totalRows).

Это было полезно?

Решение

Yea, you can simply do this:

if (response && response.data && response.data.totalRows) {
    alert(response.data.totalRows);
}

In JavaScript, a object is cast to a truthy value, when used in a if. This means you can just "dump" the variable in a if or any other boolean statement, as a check to see whether or not it exists. this blog post has some more information about it.

Please note that this will not alert anything if totalRows equals 0 (since 0 is considered a falsy value.) If you also want to alert if it's 0, use this:

if (response && response.data &&
    (response.data.totalRows || response.data.totalRows === 0)) {
    alert(response.data.totalRows);
}

Or:

if (response && response.data && response.data.totalRows !== undefined) {
    alert(response.data.totalRows);
}

Другие советы

Supposing that response.data.totalRows must be an array you can use just:

if (!response.data.totalRows.length) {
   /* empty array */
}

If you are not sure that totalRows exists you must verify:

if (
   !response ||
   !response.data ||
   !response.data.totalRows ||
   !response.data.totalRows.length
) {
   /* is empty */
}

Any value is converted in Boolean. For example: Boolean(response) will return false if response will be 0, null, undefined etc.

What about a try-catch block?

try{ alert(response.data.totalRows); }
catch(e) { alert("undefined"); }

I'd write a prototype (even if it's not recommended)

Object.prototype.isEmpty = function(){
  return (!this || this===undefined || this===null || !this.hasChildNodes())
    ?true
    :false;
}

And then just use

if(!response.isEmpty()) alert(response.data.totalRows);

It is only handy if you need the checks also elsewhere and not only one place.

Just

response && response.data && response.data.totalRows && alert(response.data.totalRows)

If the property list gets very long there is another syntax you can use, in the sample code I've created a function so it can be re used.

// args is { object: the object to check the properties of
//           properties: an array of strings with property names}
function isSet(args){
  //no checking of arguments
  var o = args.object,
  props = args.properties,
  i = -1,len = props.length
  while(typeof o !== "undefined"
    && o !== null
    && ++i<len){
    o = o[props[i]];
  }
  return (typeof o !== "undefined" 
    && o !== null)?true:false;
}
var test = {
  prop1 : {
    prop2 : "ok"
  }
};
//check if test.prop1.prop2 is set
console.log(isSet({
  object:test,
  properties: ["prop1","prop2"]
}));//=true
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top