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


当前回答

检查是否存在密钥的一种简单方法是:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true

其他回答

来自lodash.js。

var undefined;
function isUndefined(value) {
  return value === undefined;
}

它创建了一个名为undefined的局部变量,该变量用默认值(即真正的undefineed)初始化,然后将该值与变量undefine进行比较。


更新日期:2019年9月9日

我发现Lodash更新了它的实现。查看我的问题和代码。

要做到防弹,只需使用:

function isUndefined(value) {
  return value === void 0;
}

我不确定将==与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
if ( typeof( something ) == "undefined") 

这对我有用,而其他人没有。

"propertyName" in obj //-> true | false

Lodash库中有几个小助手:

isUndefined-检查值是否未定义。

_.isUndefined(undefined) // => true
_.isUndefined(null) // => false

has-检查对象是否包含属性

const object = { 'a': { 'b': 2 } }

_.has(object, 'a.b') // => true
_.has(object, 'a.c') // => false