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) {

a.hi が偽の値 ( null/ false/ 0) になることは決してないことがわかっている場合は、次のことができます。

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

typeof文字列の変数をチェックすることは、"undefined"を使用して変数がキーワード===と同じデータ型であるかどうかをチェックすることと同じです。undefinedしたがって、ネストされた if ステートメントを 1 つのステートメントに減らすことができます。

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

上記のステートメントは、 if ステートメントが実行されたときに null ではないことを前提としているaため、エラーが発生する可能性があることに注意してください。またa.hi.hello、ステートメントを評価するために存在する必要がある場合は、型である必要があるため、if偽のチェックを使用できることも当てはまります(これは偽ではありません)。aa.hiobject

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