检查对象是否已定义

检查对象是否已定义

本文介绍了检查对象是否已定义,最佳做法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从ajax请求获得以下JSON响应。

I have the following JSON response from a ajax-request.

var json = {
    "response": {
        "freeOfChargeProduct": {
        "description": "Product",
        "orderQty": 5,
        "productName": "XYZ",
        "qty": 6,
        "details": {
            "price": 55.5,
            "instock": "true",
            "focQuantity": 1
        }
    },
    "orderLineId": 4788,
    "totalOrderLinePrice": "741.36",
    "totalOrderPrice": "1,314.92",
    "totalQty": 17
};






JSON并不总是返回freeOfChargeProduct 财产。因此,如果我想获得freeOfChargeProduct价格,那么我必须执行以下操作:


The JSON dosen't always return a "freeOfChargeProduct" property. So if I want to get the "freeOfChargeProduct" price, then I have to do the following:

var getFreeOfChargeProductPrice = function() {
   var r = json.response;
   if (r && r.freeOfChargeProduct && r.freeOfChargeProduct.details) {
      return r.freeOfChargeProduct.details.price;
   }
   return null;
};






没问题。但检查对象中的每个属性都非常烦人,因此我创建了一个函数来检查对象中的属性是否已定义。


No problems. But it's very annoying to check every property in the object, so I created a function that check if a property in a object is defined.

var getValue = function (str, context) {
    var scope = context || window,
        properties = str.split('.'), i;
    for(i = 0; i < properties.length; i++) {
      if (!scope[properties[i]]) {
         return null;
      }
      scope = scope[properties[i]];
    }
    return scope;
};







var price = getValue('json.response.freeOfChargeProduct.details.price');
// Price is null if no such object exists.






现在我的问题:这是好还是检查对象中是否存在属性的错误方法?还有更好的建议/方法吗?


Now to my question: Is this a good or bad way to check if a property exists in an object? Any better suggestions/methods?

编辑:

我不喜欢不要使用&& -operator。我很懒,而且我正在寻找一种可重用的方法来检查对象(或对象的属性)是否被定义。

:)谢谢!

推荐答案

if(x && typeof x.y != 'undefined') {
    ...
}

// or better
function isDefined(x) {
    var undefined;
    return x !== undefined;
}

if(x && isDefined(x.y)) {
    ...
}

这适用于JavaScript中的任何数据类型,甚至是零的数字。如果您要检查对象或字符串,只需使用 x&&在if语句中xy ,或者如果你已经知道x是一个对象, if(xy)...

This will work for any data type in JavaScript, even a number that is zero. If you are checking for an object or string, just use x && x.y within the if statement, or if you already know that x is an object, if(x.y) ...

这篇关于检查对象是否已定义,最佳做法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:43