在Javascript中,如何确定对象属性是否存在且不为空? [英] In Javascript, How to determine if an object property exists and is not empty?
问题描述
假设我有下一个javascript对象:
Suppose I have the next javascript object:
var errors = {
error_1: "Error 1 description",
error_2: "Error 2 description",
error_3: "",
error_4: "Error 4 description"
};
如何确定属性 error_1
存在于错误
对象中,也不是空的?
How can I determine if the property error_1
exists in the errors
object and is not empty as well?
推荐答案
if(errors.hasOwnProperty('error_1')&& errors ['error_1'])
方法 hasOwnProperty
可用于确定对象是否具有指定属性作为该对象的直接属性。
The method hasOwnProperty
can be used to determine whether an object has the specified property as a direct property of that object.
errors [key]
其中 key
是一个字符串值,用于检查该值是否存在且不为null
The errors[key]
where key
is a string value checks if the value exists and is not null
检查它是否为空是否为字符串然后 typeof errors ['error_1'] ==='string'&& errors ['error_1']。length
你在哪里检查字符串的长度
to Check if its not empty where it is a string then typeof errors['error_1'] === 'string' && errors['error_1'].length
where you are checking for the length of a string
结果:
if(errors.hasOwnProperty('error_1')&& typeof errors ['error_1'] ==='string'&& errors ['error_1'] .length)
现在,如果你使用像下划线你可以使用一堆实用程序类,如 _。isEmpty
_。has(obj,key)
和 _。isString()
Now, if you are using a library like underscore you can use a bunch of utility classes like _.isEmpty
_.has(obj,key)
and _.isString()
这篇关于在Javascript中,如何确定对象属性是否存在且不为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!