繁体   English   中英

在Javascript中,如何确定对象属性是否存在并且不为空?

[英]In Javascript, How to determine if an object property exists and is not empty?

假设我有下一个javascript对象:

var errors = {
    error_1: "Error 1 description",
    error_2: "Error 2 description",
    error_3: "",
    error_4: "Error 4 description"
};

如何确定errors对象中error_1存在属性error_1并且该属性error_1为空?

if (errors.hasOwnProperty('error_1') && errors['error_1'] )

hasOwnProperty方法可用于确定对象是否具有指定属性作为该对象的直接属性。

errors[key]其中key是字符串值,它检查该值是否存在并且不为null

检查字符串是否不为空,然后在检查字符串typeof errors['error_1'] === 'string' && errors['error_1'].length地方输入typeof errors['error_1'] === 'string' && errors['error_1'].length

结果:

if (errors.hasOwnProperty('error_1') && typeof errors['error_1'] === 'string' && errors['error_1'].length)

现在,如果您使用下划线之类的库,则可以使用一堆实用程序类,例如_.isEmpty _.has(obj,key)_.isString()

要精确回答您的问题(存在且不为空),并假设您未引用空数组,则可以使用

typeof errors.error_1 === 'string' && errors.error_1.length

这是我找到并想要分享的另一个好答案(经过修改以满足我的需要):

if ("property_name" in object_name && object_name.property_name !== undefined){
   // code..
}

因此,如果我想在示例中应用它,它将看起来像:

if ("error_1" in errors && errors.error_1 !== undefined){
   // code..
}

为了检查对象是否为空,请使用此代码。

if (Object.keys(object_name).length > 0) {

  // Your code

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM