我有一个 for 循环,用于在 couchDb 的 javascript 代码中搜索数组中的值。我想把它变成一个函数。这应该相当简单,但我遇到了麻烦。这是 for 循环(效果非常好):
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].address) return;
}
}
throw({forbidden: 'doc.address is required'});
这就是我将其包装到函数中的方式:
function arrayReq(field, message) {
message = message || "Array must have a " + field;
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].field) return;
}
}
throw({forbidden: message});
}
我认为函数中的 return 应该阻止函数继续前进,但它仍然会抛出错误。有人可以告诉我我做错了什么吗?顺便说一句,如果我将字段更改为地址,它就可以正常工作。我可以不把地址变成可变变量吗?
我认为问题在于您试图将
field
用作字符串变量以及 destination[]
数组内对象的属性。
在您的代码中,如果
destination[i]
对象没有名为 field
的属性(不是 field
参数中填充的字符串值,而是名为“field”的实际属性),它永远不会评估为 true 并中断超出功能。
要使用 javascript 中的字符串表示形式访问对象的属性,请使用索引器语法。
尝试将其从
array.destination[i].field
更改为 array.destination[i][field]