开发者

jquery if check long object

开发者 https://www.devze.com 2023-03-16 10:20 出处:网络
I know that dojo has this feature开发者_开发问答, but how about jquery or any other libraries?

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消