admin管理员组文章数量:1391951
I have a function that checks if a param exists in an array of inputs. It should return false but does not.
{
...
validation: params => {
const valid = ["valid", "inputs"];
valid.forEach( v=> {
if (!params.hasOwnProperty(v)) {
return false;
}
});
return true;
}
So even when the if statement does evaluate to be true it never return false. This function always returns true no matter what.
I have a function that checks if a param exists in an array of inputs. It should return false but does not.
{
...
validation: params => {
const valid = ["valid", "inputs"];
valid.forEach( v=> {
if (!params.hasOwnProperty(v)) {
return false;
}
});
return true;
}
So even when the if statement does evaluate to be true it never return false. This function always returns true no matter what.
Share Improve this question asked Sep 27, 2018 at 2:59 Joshua BlevinsJoshua Blevins 6971 gold badge11 silver badges28 bronze badges 3-
Because the
return false
stmt is of you callback's return stmt.try setting a boolean in callback and return on basic of that or use for loop instead. – Aagam Jain Commented Sep 27, 2018 at 3:06 - 1 Possible duplicate of Short circuit Array.forEach like calling break – NullPointer Commented Sep 27, 2018 at 3:06
- If someone can post how I could refactor this code to work the way I intend I can accept that as the answer. – Joshua Blevins Commented Sep 27, 2018 at 3:07
2 Answers
Reset to default 7As an alternative, use the right tool for the job. If you want to check whether every member of an array has a certain property, use every
:
validation: params => {
const valid = ["valid", "inputs"];
return valid.every(v => params.hasOwnProperty(v));
}
You're return
is returning from the callback function of forEach
not the main function. You can't return early from a forEach
without something like a throw
. If you want to return early use a for...of
loop instead:
validation: params => {
const valid = ["valid", "inputs"];
for (v of valid) {
if (!params.hasOwnProperty(v)) {
return false; // this returns from the main function
}
};
return true;
}
本文标签: Javascript function returns true when it should return falseStack Overflow
版权声明:本文标题:Javascript function returns true when it should return false - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744666511a2618565.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论