0

I need to do something with an object. Unfortunately the system I'm doing this with (Titanium) expects values to be non-null, otherwise it will segfault. The input, however, cannot be guaranteed to provide sane objects. Here is an example:

var data = {
  foo: {
    bar: "foobar"
  }
};
function do_it(data) {
  do_something_with_non_null_value(data.foo.bar);
}

However it is entirely possible that data is any of the following:

var data = null;
var data = {
  foo: null
};
var data = {
  foo: {
    bar: null
  }
};

How can I test for a non-null value in a deep but concise manor to prevent the do_something_with_non_null_value() from crashing?

Underscore.js answers are also welcome.

4

1 回答 1

1

How about using defaults method from underscore?

function do_it(data) {

  var defaults = {
    foo: {
      bar: null
    }
  };

  data = _.defaults(data || {}, defaults);

  do_something_with_non_null_value(data.foo.bar);
}

If data is any of this:

var data = null;
var data = {
  foo: null
};

Will change the object to:

var data = {
  foo: {
    bar: null
  }
};
于 2013-07-01T13:30:39.363 回答