在Javascript中尝试执行空合并运算符时出错
正在尝试为表单提交计划字符串生成器:在Javascript中尝试执行空合并运算符时出错,javascript,jquery,error-handling,null,Javascript,Jquery,Error Handling,Null,正在尝试为表单提交计划字符串生成器: try{ top.document.getElementById("attributes").contentWindow.location = "attributeToolbar.aspx?el_id=" + (t_selected.attr("id").match(intRegex)[0] || "new") + "&opts="+ form_to_server(); }catch(err){ alert(err); //prints:
try{
top.document.getElementById("attributes").contentWindow.location = "attributeToolbar.aspx?el_id=" + (t_selected.attr("id").match(intRegex)[0] || "new") + "&opts="+ form_to_server();
}catch(err){
alert(err);
//prints: TypeError: Unable to get value of the property '0': object is null or undefined.
}
我想把一个正则表达式分成一个匹配项,如果没有匹配项,就把它分配给“new”,以显示它不在jquery对象中
上述声明的关键领域是:
(t_selected.attr("id").match(intRegex)[0] || "new")
如果您只想测试匹配项,请执行以下操作:
... intRegex.test(t_selected.attr("id")) ...
相反。如果“match”调用返回null
,数组索引操作符将给出该错误
(t_selected.attr("id").match(intRegex) || ["new"])[0]
这将为您提供完整匹配(如果找到)或字符串“new”。在到达运算符之前,错误可能会使其崩溃。请注意,没有空合并运算符,这只是一个布尔值,或者尽管在本例中具有相同的效果。但是,如果您测试的值是任何“falsy”(例如,0,false,”),那么您也会得到值
“new”
。在正常情况下,我会提取第一个元素,这就是为什么我会得到第一个匹配的元素。也许最好把它分成多行。