在Javascript中处理空值
我有一个Javascript函数,编写如下:在Javascript中处理空值,javascript,Javascript,我有一个Javascript函数,编写如下: function refresh(selection, xPath, yPath, xAnnotationSelection, yAnnotationSelection) { var coords = selection.node().__coord__; ... } 函数有时会被调用,变量selection尚未设置,这会导致引发以下异常: 未捕获的TypeError:无法读取null的属性“coord” 有什么更好的方法来
function refresh(selection, xPath, yPath, xAnnotationSelection, yAnnotationSelection) {
var coords = selection.node().__coord__;
...
}
函数有时会被调用,变量selection
尚未设置,这会导致引发以下异常:
未捕获的TypeError:无法读取null的属性“coord”
有什么更好的方法来编写语句,以便在尝试调用语句的方法之前,先检查并确保selection
不为null
伪代码:
var coords = (selection ? ((selection.node ? selection.node().__coord__: null) : null);
你可以写-:
var coords = selection && selection.node && selection.node().__coord__;
我认为发挥作用的最佳方式是:
function refresh(selection, xPath, yPath, xAnnotationSelection, yAnnotationSelection) {
const node = selection && selection.node();
if (!node) {
return null;
}
var coords = node.__coord__;
...
}
如果将selection.node更改为selection.node(),则伪代码应该可以工作。您的意思是首先检查选择是否存在,然后再在其中查找它是否应该是默认值nullcoords=selection?(selection.node()?selection.node()。_-coord__:null):null;仅对简单易读的表达式使用三元运算符。对于任何其他内容,请使用常规的
if
语句。好代码的目标不是创建花哨的一行程序,而是创建易于理解和维护的代码?(selection.node()?selection.node()。_-coord__:null):null;或者简单地将此代码const section2=selection.node()?selection.node()。_u-coord__;:null;const coords=selection?第2节:null或可以像statt const icoords=null一样使用;if(selection&&selection.node()){icoords=selection.node()。\uuuuuuuuuuuo\uuuuo}