[英]javascript : testing object property length
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) {....}
I'm using the chrome inspector and when I run the code, I don't get the error anymore. 我正在使用chrome检查器,当我运行代码时,我不再收到错误。 Is this going to work in every browser? 这会在每个浏览器中都有效吗?
Thanks. 谢谢。
As an alternative: 作为备选:
if ('Prop1' in MyObject && MyObject.Prop1.length > 0) { ... )
Or, to be even more careful: 或者,更加小心:
if (MyObject.hasOwnProperty('Prop1') && MyObject.Prop1.length > 0) { ... }
Of course that might be the wrong thing to do, depending on the nature of "MyObject". 当然,这可能是错误的,取决于“MyObject”的性质。
Yes it will work quite fine, although you can save yourself the > 0
and just do 是的它会工作得很好,虽然你可以保存自己> 0
而且就是这样
if (MyObject.Prop1 && MyObject.Prop1.length) {....}
since anything other than zero will evaluate to true. 因为零以外的任何东西都会评估为真。
Since undefined
, 0
, and ""
are all "falsy" in JavaScript, this is equivalent: 由于undefined
, 0
和""
”在JavaScript中都是“falsy”,因此这是等效的:
if(MyObject.Prop1) {
// ...
}
Rick Waldron's "Idiomatic JavaScript" is a good reference for simplifying conditional statements without sacrificing correctness. Rick Waldron的“惯用JavaScript”是一个很好的参考,可以在不牺牲正确性的情况下简化条件语句。 You can test its use yourself: 您可以自己测试它的用途:
function testProp(val) {
if(val) {
return val.length;
}
return "nope!";
}
var myObj = { stringProp : "foo",
emptyStrProp : "",
// undefinedProp is not defined
zeroProp : 0,
twelveProp : 12,
otherObjProp : document.createElement('div'),
arrayProp : [ 'a', 'b' ]
};
console.log( testProp( myObj.stringProp ) ); // => 3
console.log( testProp( myObj.emptyStrProp ) ); // => "nope!"
console.log( testProp( myObj.undefinedProp ) ); // => "nope!"
// of course if you're expecting values other than strings and undefined
// you'll have to account for them
console.log( testProp( myObj.zeroProp ) ); // => "nope!"
console.log( testProp( myObj.twelveProp ) ); // => undefined
console.log( testProp( myObj.otherObjProp ) ); // => undefined
console.log( testProp( myObj.arrayProp ) ); // => 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.