在Javascript中测试嵌套对象未定义 [英] Testing nested objects as undefined in Javascript
问题描述
可能重复:
javascript测试是否存在嵌套对象密钥
我正在尝试通过测试某个对象不是 来构建
,如果它不是 formset
的错误消息undefined undefined
,那么我最终会用该错误消息填充它。主要问题是我必须验证每个嵌套对象是否为 undefined
,这会导致一些非常难看的代码。下面是示例:
I'm attempting to construct an error message for a formset
by testing if a certain object is not undefined
, and if it's not undefined
, then I end up populating it with that error message. The main problem is that I have to validate if each nested object is undefined
, which results in some pretty ugly code. Here's the example:
errorsForField: function(fieldName, formsetName, formNumber) {
if (typeof this.model.errors != 'undefined'){
var fieldError = document.createElement('span');
$(fieldError).addClass('field-error');
// THE FOLLOWING LINE THROWS ERROR.
if (formsetName && _.isUndefined(this.model.errors[formsetName][fieldName]) != true) {
$(fieldError).text(this.model.errors[formsetname][fieldName]);
} else if (typeof this.model.errors[fieldName] != "undefined"){
$(fieldError).text(this.model.errors[fieldName]);
}
this.errors[fieldName] = fieldError.outerHTML;
return fieldError.outerHTML;
}
return false;
},
我收到一条错误消息,指出我无法确定 [fieldName]
未定义对象
this.model.errors [formsetName]
。换句话说,我必须首先确定 this.model.errors [formsetName]
是否为空,然后然后测试 [fieldname]
是 undefined
。
I get an error stating that I cannot determine [fieldName]
of an undefined object
this.model.errors[formsetName]
. In other words, I have to first determine if this.model.errors[formsetName]
is empty and then test if [fieldname]
is undefined
.
这似乎是一个非常麻烦的解决方案。有关更改此内容的任何建议吗?
This seems like a really cumbersome solution. Any suggestions for changing this?
推荐答案
您可以创建一个库函数,它将属性名称作为参数并返回最终值,如果它存在,或者为null:
You can create a library function that takes property names as parameters and returns the final value if it exists, or null:
function TryGetPropertyValue(o, propertyName1 /*, ... propertyNameN */) {
var names = [].slice.call(arguments, 1);
while (o && names.length) {
o = o[names.shift()];
}
return names.length ? null : o;
}
称之为:
var err = TryGetPropertyValue(this.model.errors, formsetName, fieldName) ||
TryGetPropertyValue(this.model.errors, fieldName);
if (err != null) {
$(fieldError).text(err);
}
如果你想要它返回 undefined
而不是 null
如果找不到该字段,您可以稍微更改该函数:
If you want it to return undefined
instead of null
if the field is not found, you can change the function slightly:
function TryGetPropertyValue(o, propertyName1 /*, ... propertyNameN */) {
var names = [].slice.call(arguments, 1);
while (o && names.length) {
o = o[names.shift()];
}
if (names.length == 0) {
return o;
}
}
这篇关于在Javascript中测试嵌套对象未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!