javascript:测试对象属性长度 [英] javascript : testing object property length
本文介绍了javascript:测试对象属性长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些带有属性的对象。我想测试看看他们是否有字符,所以我最初写了这个:
I have some objects with properties. I wanted to test to see if they had characters in them so I initially wrote this:
if (MyObject.Prop1.length > 0) {....}
但是,有时候对象可能没有某种属性所以我收到错误无法获取长度。
However, sometimes the object may not have a certain property so I was getting the error "cannot get length".
我通过写这个来改变它:
I changed it by writing this:
if (MyObject.Prop1 && MyObject.Prop1.length > 0) {....}
我正在使用chrome检查器,当我运行代码时,我不再收到错误了。这会在每个浏览器中都有效吗?
I'm using the chrome inspector and when I run the code, I don't get the error anymore. Is this going to work in every browser?
谢谢。
推荐答案
作为替代方案:
if ('Prop1' in MyObject && MyObject.Prop1.length > 0) { ... )
或者,更加小心:
if (MyObject.hasOwnProperty('Prop1') && MyObject.Prop1.length > 0) { ... }
当然这可能是错误的,取决于MyObject的性质。
Of course that might be the wrong thing to do, depending on the nature of "MyObject".
这篇关于javascript:测试对象属性长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文