相关疑难解决方法(0)

从javascript函数返回`undefined`或`null`更好吗?

我有一个我写的功能,基本上看起来像这样:

function getNextCard(searchTerms) {
  // Setup Some Variables

  // Do a bunch of logic to pick the next card based on termed passed through what I'll call here as 'searchTerms' all of this logic is omitted because it's not important for my question.
  // ...

  // If we find a next card to give, than give it
  if (nextCardFound)
    return nextCardFound;

  // Otherwise - I'm returning undefined
  return undefined;
}
Run Code Online (Sandbox Code Playgroud)

问题:在这里返回"null"会更好吗?

我可以通过我想要的任何东西 - 显然......我只是不确定什么是最好用的东西.

调用此函数的代码知道如何处理未定义的(除非出现可怕的错误,否则实际上不会真正发生)

我问这个问题的原因是我听到某些地方听起来像"不要将未定义的变量分配给变量"或其他东西 - 它会使调试变得更难.所以,我可以看到null传回来的事实告诉我返回工作 …

javascript null return function undefined

68
推荐指数
4
解决办法
5万
查看次数

我何时使用null初始化JavaScript中的变量?

我已经看到了声明变量并设置为undefined和null的不同代码示例.如:

var a; // undefined - unintentional value, object of type 'undefined'
var b = null; // null - deliberate non-value, object of type 'object'
Run Code Online (Sandbox Code Playgroud)

如果遵循这些声明的代码为a或b赋值,那么使用一种声明而不是另一种声明的原因是什么?

javascript variables null undefined

36
推荐指数
4
解决办法
5万
查看次数

标签 统计

javascript ×2

null ×2

undefined ×2

function ×1

return ×1

variables ×1