返回不工作的条件。尽管 console.log 工作正常。问题是函数总是返回 false。
function func(obj, input) {
if (input === obj) {
console.log('Here it works');
return true; //expected return tr
};
for (let key in obj) {
func(obj[key], input);
}
return false;
最佳答案
您需要检查 for
循环内调用的返回值,并返回 true
退出。
function contains(obj, input) {
if (input === obj) {
return true;
}
if (!obj || typeof obj !== 'object') { // check for objects
return false; // and exit if not with false
}
for (let key in obj) {
if (contains(obj[key], input)) { // check for true
return true; // return only if true
}
}
return false;
}
console.log(contains('a', 'a'));
console.log(contains('a', 'b'));
console.log(contains({ foo: { bar: { baz: 42 } } }, '42'));
console.log(contains({ foo: { bar: { baz: 42 } } }, 42));
关于javascript - 返回条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52464520/