jquery if check long object
I know that dojo has this feature开发者_开发问答, but how about jquery or any other libraries?
$.ifObject(foo.bar.baz.qux[0])
if (foo && foo.bar && foo.bar.baz && foo.bar.baz.qux[0])
Assuming arbitrary size of the object nesting, I'm looking for a sugar function that will check whether or not the object I'm looking for is defined, and not crash the server along the way.
In case you want to dive into coffee script, it has a great feature in the ?
operator.
if foo?.bar?.baz?.qux?[0]
alert 'yay!'
Which compiles to this nasty, yet very efficient, javascript
var _ref, _ref2, _ref3;
if (typeof foo !== "undefined" && foo !== null ? (_ref = foo.bar) != null ? (_ref2 = _ref.baz) != null ? (_ref3 = _ref2.qux) != null ? _ref3[0] : void 0 : void 0 : void 0 : void 0) {
alert('yay!');
}
The simplest way to do this would be to enclose the variable reference in a try-catch
block:
try {
var val = foo.bar.baz.qux[0];
// succeeded: use val
} catch (ex) {
// failed: do something else
}
精彩评论