0

I don't recollect exactly what its called but php checks and exists as soon as it finds one false value in a function, like so :

// php
if(isset(a["hi"]) && isset(a["hi"]["hello"])) {

}

here if a["hi"] is not set, it will not bother to check the next a["hi"]["hello"].

to check something like this in javascript you'd need to nest

// js
if(typeof(a["hi"]) != "undefined") {
    if(typeof(a["hi"]["hello"]) != "undefined") {

    }
}

Can we do php style lazy checking in javascript? (I may not be using the best method to check if an element exists in a multi-dimentional array, if there is a succinct way of doing this, would love to know.)

thanks!

4

3 回答 3

2

You could use in to check property existence.

if(a && ('hi' in a) && ('hello' in a['hi'])) {

}
于 2012-07-09T05:07:23.163 回答
1
if(a.hi === undefined && a.hi.hello === undefined) {

if you know that a.hi can never be a falsey value (null / false / 0) you can do

if(!a.hi && !a.hi.hello) {
于 2012-07-09T05:08:35.147 回答
1

检查typeof字符串的a变量"undefined"相当于使用===检查变量是否与undefined关键字的数据类型相同。因此,您可以将嵌套的 if 语句减少为单个语句:

if(a.hi !== undefined && a.hi.hello !== undefined) {
  // do something with a.hi.hello
}

值得注意的是,上面的语句假定aif 语句发生时不为空,这可能会导致错误。如果您需要a.hi.hello在场if以评估语句,那么您可以使用虚假检查aa.hi因为它们需要是object类型(非虚假):

if(!!a && a.hi && a.hi.hello !== undefined) {
  // do something with a.hi.hello
}
于 2012-07-09T07:50:13.477 回答