且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-29 08:54:40

我认为没有***的方法,甚至标准函数有时也会选择其中一个.

I will argue there is no best way, and even standard functions sometimes choose one or the other.

例如:

  • [[原型]]

  • [[Prototype]]

普通对象有一个 [[Prototype]] 内部槽,它决定了它们从哪个其他对象继承.当然,必须有一种方法可以说一个对象不继承自任何其他对象.在这种情况下,没有这样的对象"使用 null 表示.

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

期望返回一个属性描述符,即描述属性(例如值、可写性、可枚举性和可配置性)的对象.但是,该属性可能不存在.在这种情况下,使用 undefined 表示没有这样的属性".

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

应该返回具有给定 ID 的元素.但是,可能没有具有该 ID 的元素.在这种情况下,没有这样的元素"使用 null 表示.

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.

因此,只需选择您喜欢或认为对您的具体情况更有意义的任何内容.

So just choose whatever you prefer or think makes more sense for your specific case.