如何检查JavaScript中的对象属性是否未定义?


当前回答

有一种非常简单的方法。

您可以使用可选链接:

x = {prop:{name:"sajad"}}

console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined

or

if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error

您甚至可以对函数或数组使用可选的链接。

截至2020年年中,这一点尚未得到普遍实施。查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

其他回答

我不确定将==与typeof一起使用的起源,按照惯例,我在许多库中都使用了它,但typeof运算符返回字符串文本,我们事先就知道了,所以为什么还要对其进行类型检查呢?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient

Use:

要检查属性是否未定义,请执行以下操作:

if (typeof something === "undefined") {
    alert("undefined");
}

要检查属性是否未定义,请执行以下操作:

if (typeof something !== "undefined") {
    alert("not undefined");
}
function isUnset(inp) {
  return (typeof inp === 'undefined')
}

如果变量已设置,则返回false;如果未定义,则返回true。

然后使用:

if (isUnset(var)) {
  // initialize variable here
}

有一种非常简单的方法。

您可以使用可选链接:

x = {prop:{name:"sajad"}}

console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined

or

if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error

您甚至可以对函数或数组使用可选的链接。

截至2020年年中,这一点尚未得到普遍实施。查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

在最近的JavaScript版本中,引入了新的链接运算符,这可能是检查属性是否存在的最佳方法,否则它将给您提供未定义的

参见下面的示例

  const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

我们可以替换这个旧语法

if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}

使用更简洁的语法

if( response?.data?.someData?.someMoreData) {}

IE、Opera、safari和samsund android不支持此语法

有关详细信息,请查看此URL

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining