6

当一个变量缺少一个字段并且用户看到这个或那个变量没有这个或那个属性的警告时,我遇到了这个问题。在简单的情况下,它非常简单。

if(field)
  doSomething(field.subField);

然而,在经验情况下,我发现自己陷入了这种荒谬的过度检查。

if(!data 
  || !data.records 
  || !data.records[0] 
  || !data.records[0].field 
  || !data.records[0].field.id)
    return null;
doSomething(data);

我的意思是,来吧 - 如果我是水管工,而不是开发人员,管道式的东西看起来像。所以,我有一种非常强烈的感觉,我的支票虽然足够,但可能有点太过分了。JS 中是否有关于何时执行检查的约定?

4

2 回答 2

6

我只是提出一个有争议的意见。

在 JavaScript 中,不要费心检查null实际不应该发生的地方的值。换句话说,您检查每个嵌套属性是否存在空值的想法有点矫枉过正,只会使您的脚本复杂化。

根据我的经验,我学会了让脚本错误发生。这对于编写 C 代码或数据库代码的人来说有点违反直觉,其中未处理的null可能会使服务器崩溃或损坏数据,但是在脚本世界中,最好尽早发现错误。如果您的页面继续加载而没有任何意外发生的迹象,那么稍后当用户单击按钮或提交表单时,它只会以奇怪的错误形式出现。

我的建议

null 当您愿意为此做些什么时才进行检查。如果您有一个 Web 服务可能会null在出现问题时返回 a,然后检查它并显示一条错误消息。如果你得到一个非空值,假设它是一个有效值并继续。没有理由在你的整个脚本中乱扔空检查,这实际上不会给你的程序带来任何真正的好处。

于 2013-01-17T17:34:30.610 回答
2

Normally you would make sure that if an object exists, it always has a basic set of properties that makes it usable.

For example, if the variable data has a value at all, it would be an object that has records property that always is an array, even if it is empty. If the array contains anything, it should always be objects that has a field property, which is an object that always has an id proprty. That would cut down the checks to:

if (!data || data.records.length == 0) {
  return null;
}
于 2013-01-17T17:28:49.857 回答