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

时间:2015-05-24 14:20:44

标签: javascript arrays string for-loop indexof

在字符串数组中,如果循环发现其中一个字符串不是我们要查找的字符串,则循环返回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()

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

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

既然你做了

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

然后,即使数组中没有这些括号中的一个,条件也将返回false。

答案 2 :(得分:0)

您已使用

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

所以如果你需要测试你需要测试2-d数组的字符串

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

答案 3 :(得分:0)

这应该这样做:

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

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

查找&#34;()&#34;的所有实例和&#34; {}&#34;

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

相关问题