您可以使用可选链接 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
例子:
// Access Properties
user?.name; // user might be null/undefined
user.name?.firstName // user will be available however name is not guaranteed.
// Access array values
addresses?.[index]; // array addresses might be undefined
// May be function??
user.getGeolocation?.(); // If the function exists execute it.
稍微不相关但围绕处理 null/未定义的东西是另一个称为空合并运算符 ?? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
// Example:
function foo(input) // some Array as input {
//.. Some stuff
return [input??[]].concat(bar); //if input is empty ignore and concat bar on an empty array and return.
}
//----
const defaultVal = 'someVal';
...
const val = this.someObj.prop1??defaultVal;
下面是在可选链成为 Javascript 原生之前过时的解决方案:
您可以这样做,因为没有内置的方法可以做到这一点:
var x = (user || {}).name;
- 如果用户未定义/为空,您将得到未定义的结果
- 如果定义了用户,您将获得名称属性(可以设置或未定义)。
如果未定义用户(空),这不会破坏脚本。
但是用户变量必须在范围内的某个位置声明,即使它的值没有定义。否则,您将收到错误消息,提示用户未定义。
类似地,如果在全局范围内,那么您可以显式检查此变量作为全局范围的属性,以避免上述错误
ex:
var x = (window.user || {}).name; // or var x = (global.user || {}).name;
为了安全执行功能,
var noop = function(){}; //Just a no operation function
(windowOrSomeObj.exec || noop)(); //Even if there is no property with the name `exec` exists in the object, it will still not fail and you can avoid a check. However this is just a truthy check so you may want to use it only if you are sure the property if exists on the object will be a function.