Javascript 从javascript函数返回`undefined`还是`null`更好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37980559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it better to return `undefined` or `null` from a javascript function?
提问by Jeremy Iglehart
I have a function which I have written which basically looks like this:
我有一个我写的函数,它基本上是这样的:
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;
}
Question: Would it be better to return "null" here?
问题:这里返回“null”会更好吗?
I can pass whatever I want back - obviously... I just wasn't sure what is the best thing to use.
我可以传递我想要的任何东西 - 显然......我只是不确定什么是最好的使用。
The code that calls this function knows how to deal with undefined (it actually won't ever really happen unless something goes horribly wrong)
调用此函数的代码知道如何处理 undefined (除非出现严重错误,否则它实际上永远不会发生)
The reason I'm asking this question is that I heard somewhere something that sounded like "Don't assign undefined to variables" or something - that it will make it harder to debug. So, the fact that I can see that null
gets passed back tells me that the return is working - but basically function similar to undefined
.
我问这个问题的原因是我在某处听到了一些听起来像“不要将未定义分配给变量”之类的东西 - 这会使调试变得更加困难。因此,我可以看到null
被传回的事实告诉我返回正在工作 - 但基本上功能类似于undefined
.
Documentation:
文档:
Mozilla DocsDidn't answer my question... google didn't either :\
Mozilla Docs没有回答我的问题......谷歌也没有:\
This SO Question- was way too broad for what I'm trying to figure out here.
这个SO问题-对于我在这里试图弄清楚的内容来说太宽泛了。
采纳答案by Oriol
I will argue there is no best way, and even standard functions sometimes choose one or the other.
我会争辩说没有最好的方法,甚至标准功能有时也会选择其中之一。
For example:
例如:
[[Prototype]]
Ordinary objects have a [[Prototype]] internal slot, which determines from which other object they inherit from. Of course, there must be a way to say that an object does not inherit from any other one. In this case, "there is no such object" is represented using
null
.Object.getOwnPropertyDescriptor
It is expected to return a property descriptor, that is, an object which describes a property (e.g. value, writability, enumerability and configurability). However, the property may not exist. In this case, "there is no such property" is represented using
undefined
.document.getElementById
It is expected to return the element with the given ID. However, there might be no element with that ID. In this case, "there is no such element" is represented using
null
.
[[原型]]
普通对象有一个 [[Prototype]] 内部槽,它决定了它们从哪个其他对象继承。当然,必须有一种方法可以说一个对象不从任何其他对象继承。在这种情况下,“没有这样的对象”用 表示
null
。Object.getOwnPropertyDescriptor
期望返回属性描述符,即描述属性(例如值、可写性、可枚举性和可配置性)的对象。但是,该属性可能不存在。在这种情况下,“没有这样的属性”用 表示
undefined
。document.getElementById
期望返回具有给定 ID 的元素。但是,可能没有具有该 ID 的元素。在这种情况下,“没有这样的元素”用 表示
null
。
So just choose whatever you prefer or think makes more sense for your specific case.
因此,只需选择您喜欢或认为对您的特定情况更有意义的任何内容。
回答by chiliNUT
Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.
未定义通常是指尚未(尚未)分配值的内容。Null 指的是绝对没有价值的东西。在这种情况下,我建议返回 null。请注意,没有指定返回值的函数会隐式返回 undefined。
From the ECMAScript2015 spec
来自 ECMAScript2015 规范
4.3.10 undefined value
primitive value used when a variable has not been assigned a value
4.3.12 null value
primitive value that represents the intentional absence of any object value
4.3.10 未定义值
未为变量赋值时使用的原始值
4.3.12 空值
表示有意不存在任何对象值的原始值
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
Further reading:
进一步阅读:
回答by ngryman
I will give you my personal opinionated way of choosing between the two.
我会给你我个人的观点,在两者之间做出选择。
My simple question is: could the value, given another input/state/context be defined to something?
我的简单问题是:给定另一个输入/状态/上下文的值是否可以定义为某物?
If the answer is yes then use null
else use undefined
. More generally any function returning an object should return null
when the intended object does not exist. Because it could exist given another input/state/context.
如果答案是肯定的,那么使用null
else use undefined
。更一般地,null
当预期的对象不存在时,任何返回对象的函数都应该返回。因为它可以存在给另一个输入/状态/上下文。
null
represents the absence of valuefor a given input/state/context. It implicitly means that the conceptof the value itself exist in the context of your application but may be absent.
In your example the concept of a next card exists but the card itself may not exist. null
should be used.
null
表示给定输入/状态/上下文的值缺失。它隐含地意味着值本身的概念存在于您的应用程序的上下文中,但可能不存在。在您的示例中,下一张卡片的概念存在,但卡片本身可能不存在。null
应该使用。
undefined
implicitly represents the absence of meaningof that value in your application's context. For example, if I manipulate a user
object with a given set of properties and I try to access the property pikatchu
. The value of this property should be set to undefined
because in my context it doesn't make any sense to have such a property.
undefined
隐式表示该值在您的应用程序上下文中没有意义。例如,如果我操作user
具有给定属性集的对象并尝试访问该属性pikatchu
。应该将此属性的值设置为 ,undefined
因为在我的上下文中,拥有这样的属性没有任何意义。
回答by vadi taslim
undefined
is not something you should assign to. You might want to consider to return something else other than undefined
. In your case, even if you don't return anything at all, the result will be undefined
already. So, I'd suggest to go with null
instead.
undefined
不是你应该分配给的东西。您可能需要考虑返回除undefined
. 在您的情况下,即使您根本不返回任何内容,结果也undefined
已经存在。所以,我建议null
改用。
Consider this sample,
考虑这个样本,
function getSomething() {
// .. do something
return undefined;
}
function doSomething() {
// .. I'm not gonna return anything.
}
var a = getSomething();
var b = doSomething();
Above sample result in a === b
, which is undefined
. The difference is that you save 1 statement execution.
以上样本结果为a === b
,即undefined
。不同之处在于您节省了 1 条语句执行。
回答by masterxilo
Here's an example where undefined
makes more sense than null
:
这是一个undefined
比null
以下更有意义的示例:
I use a wrapper function for JSON.parse
that converts its exception to undefined
:
我使用包装函数JSON.parse
将其异常转换为undefined
:
// parses s as JSON if possible and returns undefined otherwise
// return undefined iff s is not a string or not parseable as JSON; undefined is not a valid JSON value https://stackoverflow.com/a/14946821/524504
function JSON_parse_or_undefined(s) {
if ("string" !== typeof s) return undefined
try {
const p = JSON.parse(s)
return p
} catch (x){}
return undefined
}
Note that null
is valid in JSON while undefined
is not.
请注意,null
它在 JSON 中有效,而在 JSONundefined
中无效。
回答by Dan
Depends on what u need to do with the returned value.
取决于你需要对返回的值做什么。
typeof null returns an object. that object has a value of undefined
typeof null 返回一个对象。该对象的值为 undefined
typeof undefined returns undefined
typeof undefined 返回 undefined
回答by Ryan Laboucane
I think it is very debatable what to use. I prefer code that is semantically as accurate as possible, so I think undefined
is appropriate in this case.
我认为使用什么是很有争议的。我更喜欢语义上尽可能准确的代码,所以我认为undefined
在这种情况下是合适的。
I think of null
assignments as meaning "a variable set to nothing". This is as opposed to undefined
meaning "this thing isn't there at all"
我认为null
赋值意味着“一个没有设置的变量”。这与undefined
“这东西根本不存在”相反
As a previous answer pointed out, returning undefined
has issues, and it's completely up to you whether that bothers you. It wouldn't bother me.
正如之前的答案所指出的,返回undefined
有问题,这是否会困扰您完全取决于您。它不会打扰我。
回答by FK82
I would argue that in this case, null
should be returned.
我会争辩说,在这种情况下,null
应该退回。
If you consider the question from a theoretical computer science point of view then undefinedis used to indicate non-termination/ non-computability(i.e. the placeholder for an undefined point x
of a partial functionf
which is often written f(x) = ⊥
).
如果您从理论计算机科学的角度考虑这个问题,那么undefined用于表示不可终止/不可计算性(即通常编写x
的偏函数的未定义点的占位符)。f
f(x) = ⊥
getNextCard
however seems to be able to compute the next card (if it exists) and also be able to compute if there is no next card. In other words, the function is totalsince it terminates for every input.
getNextCard
但是似乎能够计算下一张卡(如果存在),也可以计算是否没有下一张卡。换句话说,该函数是完整的,因为它对每个输入都终止。
That being said, a special valuesignalling termination without meaningful result (i.e. "there's no card I can return for this input") is required and this for me is null
not undefined
.
也就是说,需要一个没有有意义结果的特殊值信号终止(即“我无法为此输入返回卡”),而这对我来说null
不是undefined
。
NOTES:
笔记:
You can see some support for this argument in some other typed languages as well where termination without meaningful result are expressed using an option type(sometimes also referred to as nullable type). An example for this is is Maybein Haskell.
您也可以在其他一些类型化语言中看到对此参数的一些支持,其中使用选项类型(有时也称为可空类型)表示没有有意义结果的终止。因为这是一个例子就是也许在哈斯克尔。
On the other hand, we of course do not know what undefined
in JavaScript is really supposed to mean. So, the analogy to undefinedis a bit tenous. Moreover, since we always want to work with total functions, this amounts to saying "never return undefined
from a function". Which seems to be a bit strict, since it would limit the use of undefined
to properties/ variables which have not been set.
另一方面,我们当然不知道undefined
JavaScript 中的真正含义。因此,与undefined的类比有点棘手。此外,由于我们总是想使用全函数,这相当于说“永远不要undefined
从函数返回”。这似乎有点严格,因为它会限制对undefined
尚未设置的属性/变量的使用。
In the end, my personal preference is never to return undefined
where I can return null
and I would also argue that this is the better coding convention (because among other things x !== null
is shorter than typeof x !== 'undefined'
).
最后,我个人的偏好是永远不要返回undefined
我可以返回的地方null
,我也认为这是更好的编码约定(因为除其他外,x !== null
它比 短typeof x !== 'undefined'
)。
回答by rubendmatos1985
My personal opinion according to my experience is don't use undefined and null if you don't want to crash your code. At least I would avoid it personally. There is a lot of functions in Javascript that return undefined and ok we must to use to it. But when you design your code don't use it. It is important to always return something "false"
at least. If you have an array for example and you map over it. It is not good to return [undefined, undefined.....]
or just undefined
. Is better if you keep the type of the original array.
Example:
根据我的经验,我个人的意见是,如果您不想使代码崩溃,请不要使用 undefined 和 null。至少我个人会避免它。Javascript 中有很多函数返回 undefined ,我们必须使用它。但是当你设计你的代码时不要使用它。"false"
至少总是返回一些东西很重要。例如,如果您有一个数组并对其进行映射。返回[undefined, undefined.....]
或只是返回都不好undefined
。如果保留原始数组的类型会更好。例子:
const mapper:Map <string[],boolean[]>
['i', 'dont', 'use', 'null or undefined'] -> [false, true, false, true, false]
or ['', dont, '', '', use]
or al the stuff above and then filter(v => v)
that will keep all undefined and null out
That's the idea.
I try all the time to avoid it. Because a null
or undefined
can easily crash your code
这就是想法。我一直在努力避免它。因为null
orundefined
很容易使您的代码崩溃
回答by Maciej Paprocki
First answer is right. They have theoretically different meaning. However it's not always clear which to pick up.
第一个答案是对的。它们在理论上具有不同的含义。然而,并不总是清楚要选择哪个。
I tend to use null in my development although I think that's completely subjective thing.
我倾向于在我的开发中使用 null 虽然我认为那是完全主观的事情。
I use that mostly because:
我使用它主要是因为:
undefined variable might be overwritten in old browsers so returning it is a little bit more complicated. This same issue forces you to use
typeof var === 'undefined'
when getting function results. linkOther languages tend to use null widely, a lot of them don't even have undefined (php for example). That gives me kind of consistency when quickly swapping between languages.
undefined 变量可能会在旧浏览器中被覆盖,因此返回它有点复杂。同样的问题迫使您
typeof var === 'undefined'
在获取函数结果时使用。关联其他语言倾向于广泛使用 null,其中很多甚至没有 undefined(例如 php)。在语言之间快速切换时,这给了我某种一致性。