在字符串数组中查找特定字符串

Finding a specific string in array of strings

在一个字符串数组中,如果发现其中一个字符串不是我们要找的,则循环returns false

如果没有找到不匹配的字符串,则数组是正确的,应该 return true。它保持 returning false 即使数组没有 "mistakes"

我试过使用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()

将数组更改为:var testArr = ['()', '{}', '[]']

既然你这样做了

 if (testArr.indexOf("()") == -1 || testArr.indexOf("{}") == -1 ||
        testArr.indexOf("[]") == -1)

那么即使数组中缺少这些括号之一,条件也会 return 为假。

您已经使用

创建了一个数组
var testArr = ['()', '{}', '()']

所以如果你需要测试你需要测试二维数组的字符串

if (testArr[0].indexOf("()") == -1

在第二种方法中,您可以使用 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();

应该这样做:

var testArr = ['()', '{}', '()'];

if(testArr.some(function(e){ return /(){}/g.test(e) })){
   console.log("found");
} else {
   console.log("not found");   
}

查找“()”和“{}”的所有实例

https://jsfiddle.net/dhoh1932/1/