在字符串数组中,如果循环发现其中一个字符串不是我们要查找的内容,则返回 false
。
如果没有找到不匹配的字符串,则数组是正确的,并且应该返回true
。即使数组没有“错误”,它也会不断返回 false
我尝试过使用indexOf
、for循环和while循环,但都没有成功。
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()
最佳答案
在第二种方法中,您可以使用 AND 运算符来解决此问题。
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();
关于javascript - 在字符串数组中查找特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30424517/