我有一个在某些情况下未声明的变量,我想在jQuery模板中使用它。这是我想要达到的目的,但是它抛出“未定义付款方式”异常:

{{if payment_method && (payment_method.id == $value.id)}}
    // this throws an exception when payment_method is undeclared!
{{/if}}

这有效:
{{if payment_method }}
    {{if payment_method.id == $value.id}}
        // nested works!
    {{/if}}
{{/if}}

但是我不太喜欢嵌套解决方案,因为我大量使用它。我很清楚为什么第一种情况会引发错误,我正在寻找一种可能的解决方法,而无需诉诸第二种解决方案。

这个问题可能归结为js中的问题,即检查未声明/ undefined variable 的属性。这有效:
if("undefined" !== typeof undefinedVariable) {
    // this works just fine also for undeclared variables
}

但这不是:
if("undefined" !== typeof undefinedVariable.property) {
    // this throws an exception
}

有任何想法吗?

最佳答案

使用未定义/未声明的变量时,它不会引发任何异常,但是使用它的属性时,它会抛出异常。不过,这有点模糊。

如果您通过typeof检查此未声明变量的存在,它将评估为 false (至少我认为是这样,当它是唯一条件时才这样做……),并且不会继续检查其他条件。如果仅通过其名称检查它的存在,则它的计算结果为false,但下一个条件仍然得到计算...

无论如何,这不会引发任何异常:

if(typeof undeclaredVariable !== "undefined" && typeof undeclaredVariable.property !== "undefined") {
    // this works just fine
}

而且也没有:
if(typeof undeclaredVariable !== "undefined" && undeclaredVariable.property) {
    // this also works just fine but is shorter
}

但是这样做:
if (undeclaredVariable && undeclaredVariable.property) {
    // the conditional clause does not stop at undeclaredVariable but also checks for undeclaredVariable.id where it throws an exception
}

在不了解如何评估条件的真正机制的情况下,(成功测试了)我的问题的答案:
{{if typeof payment_method !== "undefined" && payment_method && (payment_method.id == $value.id)}}

编辑:使用未定义/未声明的变量会在js中引发异常,但在jQuery tmpl中不会。

js:
if (undeclaredVariable) {
    // throws an exception
}

jQuery Tmpl:
{{if undeclaredVariable}}
    // evaluates to false, but does not throw an exception
{{/if}}

09-19 10:32