3

Time and again I have to deal with code like consider following hypothetical example:

if (node.data.creatures.humans.women.number === Infinity) {
  // do-someting
}

Now, problem is that if node is undefined this condition will break. Similarly, it will break if node.data is undefined, node.data.creatures is undefined and so on.

So I end up using following kind of long condition:

if (node && node.data && node.data.creatures && node.data.creatures.humans && node.data.creatures.women && node.data.creatures.humans.women.number === Infinity) {
  // do-someting
}

Now, imagine I have to use parts of that JSON object in many other parts of code too.

The code suddenly starts looking very ugly. Is there a better way of avoiding errors like "Cannot call property of undefined" kind of errors due to the first condition I mentioned such that the code looks better too.

そのような状況にどのように対処しますか?

4

3 に答える 3

1

これが私が使用しているものです。「最適化された」方法ではないかもしれませんが、それは私にとってはうまくいきます:

walkObject = function(obj, path) {
  var i = 0,
    part = void 0,
    parts = path.split('.');

  while (obj && (part = parts[i++])) {
    obj = obj[part];
  }
  return obj;
};

このメソッドは、オブジェクトと、テストするプロパティのドット表記を含む文字列を受け取ります。

// the object
var obj = { a: { b: {c: [1,2,3], d: "aa"} } };

// tests
console.log("a,b,c", walkObject(obj, 'a.b.c')); // [1,2,3]
console.log("a,b,e", walkObject(obj, 'a.b.e')); // undefined
console.log("z,b,e", walkObject(obj, 'z.b.e')); // undefined
于 2016-03-07T08:20:46.263 に答える
0

潜在的に有害な部分をtry-でラップできますcatch:

try {
    if (node.data.creatures.humans.women.number === Infinity) {
        // do-someting
    }
} catch () {
    console.log(e);
}

別の方法で、おそらくもう少し洗練された方法は、予想されるオブジェクト構造を定義し、たとえばjQuery.extend()を使用して実際のデータとマージすることです。

var nodeTemplate = {
    data: {
        creatures: {
            humans: {...}
        }
    }
}

これにより、構造が期待どおりであり、存在しないフィールドにいくつかのデフォルト値があることが確認されます。

次にマージします。

node = $.extend(nodeTemplate, node);
于 2016-03-07T08:20:34.350 に答える
0

のプロパティにアクセスしようとすることundefinedキャッチ可能 TypeErrorであるため、次を使用できますtry..catch

try {
    if (node.data.creatures.humans.women.number === Infinity) {
        // do something
    }
} catch (e) {
    // property doesn't exist
}
于 2016-03-07T08:19:06.700 に答える