[英]javascript testing for object property
I have a string like this: 我有一个像这样的字符串:
var TheDate = "6.14.2012";
and I have an object MyObject
that has properties that may match that string. 我有一个对象MyObject
,其属性可以匹配该字符串。 However, when I write this: 但是,当我这样写:
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
the conditions never seem to evaluate to true even though I know the property doesn't exist. 即使我知道财产不存在,条件似乎永远不会评估为真。
What am I missing?? 我错过了什么?
Thanks. 谢谢。
Existence of Own Property 自有财产的存在
If you want to check for the existence of a property use .hasownProperty()
... 如果要检查是否存在属性,请使用.hasownProperty()
...
if (MyObject.hasOwnProperty(TheDate)) {
Existence of Own Or Inherited Property 自有或继承财产的存在
If the property may be inherited, to test for existence use the in
operator... 如果属性可以继承,为了测试存在使用in
运算符...
if (TheDate in MyObject) {
null
or undefined
value test for Own Or Inherited Property Own或Inherited Property的null
或undefined
值测试
If it's not existence, but rather a value test, and you want to test for null
or undefined
, then use this... 如果它不存在,而是一个值测试,并且你想测试null
或undefined
,那么使用这个......
if (MyObject[TheDate] == null) {
This will check for both null
and undefined
. 这将检查null
和undefined
。
The problem is with the quotes around undefined ;) 问题在于未定义的引号;)
Change 更改
if (MyObject[TheDate] === null || MyObject[TheDate] === 'undefined') { .... }
to 至
if (MyObject[TheDate] === null || MyObject[TheDate] === undefined) { .... }
It should work :) 它应该工作:)
If you want to use the string "undefined"
rather than the undefined
object, the way to do this is to check the "typeof", which returns a string. 如果你想使用字符串"undefined"
而不是undefined
对象,那么执行此操作的方法是检查“typeof”,它返回一个字符串。 In this case, if you're looking to test if it's set to "undefined": 在这种情况下,如果您要测试它是否设置为“undefined”:
if ( MyObject[TheDate] === null || typeof MyObject[TheDate] === 'undefined' ) { .... }
Try the following 请尝试以下方法
if ( (MyObject[TheDate] === null) || (typeof MyObject[TheDate] === 'undefined') {
....
}
You were checking whether your property contains the String 'undefined'
and not whether its value is currently undefined
. 您正在检查您的属性是否包含字符串'undefined'
而不是它的值是否当前undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.