我在变量上随机得到 undefined ,所以检查变量是否已定义并且具有字符串长度是否有点矫枉过正?

I get random undefined on variables so Is this overkill for checking if variable is defined and has string length?

我似乎一直看到未定义在我们引用的应用程序中弹出 foo.length

这是否是检查变量是否为

的正确语法?

使用 lodash

if(!_.isNil(foo) && foo.length)

或者只是打字稿

// option 1
if(foo && foo.length)

// option 2
if(foo)

使用 lodash 是否值得使用,或者它是否会影响性能?

这完全取决于该变量的类型。但是,如果 foostring[] | null | undefined,那么您只需检查其真实性并继续前进:

if (foo) {
  // foo is `string[]` in this conditional scope
}

或者您可以使用 foo?.length 并提供默认值:

const size = foo?.length ?? 0 // length of array, if undefined use zero.

对这种事情使用 lodash 有点过分了。


所以考虑到所有检查数组是否存在 不为空,这可能是最简单的最好方法:

if (foo && foo.length > 0)