【发布时间】:2015-08-06 02:50:45
【问题描述】:
在字符串数组中,如果循环发现其中一个字符串不是我们要查找的字符串,则循环返回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()
【问题讨论】:
-
testArr.indexOf("[]")显然失败了,因为这是一个逻辑 OR,如果其中任何一个失败,它会返回 false ?
标签: javascript arrays string for-loop indexof