In an array of strings, a loop returns false
if it finds that one of the strings is not what we are looking for.
If it doesn't find an unmatching string, the array is correct and it should return true
. It keeps returning false
even when the array has no "mistakes"
I have tried using indexOf
, for loop and while loops, all of them unsuccessful.
function brackets() {
var testArr = ['()', '{}', '()']
/* Method 1 --- returns false even when the parenthesis are ok, I guess
it's because the indexOf only searches for the first element that matches
the criteria */
if (testArr.indexOf("()") == -1 || testArr.indexOf("{}") == -1 ||
testArr.indexOf("[]") == -1) {
return false
} else {
return true
}
/* Method 2 --- for loop. Same story, returns false, even when all
testArr[i] === any of the cases and none of them is !==, it behaves as if it was
false. I'm not sure why */
for (i = 0; i < testArr.length; i++) {
if (testArr[i] !== "()" || testArr[i] !== "{}" || testArr[i] !== "[]") {
return false
}
}
return true
}
brackets()
In the second method you can use an AND operator to solve this problem.
function brackets() {
var testArr = ['()', '{}', '()'];
/* Method 2 --- for loop. Same story, returns false, even when all
testArr[i] === any of the cases and none of them is !==, it behaves as if it was
false. I'm not sure why */
for (i = 0; i < testArr.length; i++) {
if (testArr[i] !== "()" && testArr[i] !== "{}" && testArr[i] !== "[]") {
return false;
}
}
return true;
}
brackets();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments