我有一个变量,在某些情况下没有声明,我想在jQuery模板中使用它.这是我想要实现的,但它抛出* payment_method未定义*异常:
{{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中检查未声明/未定义变量属性的问题.这有效:
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}}