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

标签 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()

最佳答案

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

相关文章:

c - 将数组传递给 scanf 函数将不起作用

python - 具有可变数字参数的 Python 中的字符串格式

c# - 为什么字符串是引用类型?

javascript - 我们如何访问 Node.js 应用程序之外的内存?

javascript - 当 lodash 有余数时,如何将排序的数组排序到列中?

java - 如何使用数组编写程序,其中用户输入数字,程序返回相应的结果

arrays - 如何从 Perl 散列中删除空数组/引用?

python - 修改多列的打印功能 - Python

javascript - 为什么这些元素不显示行内 block ?

javascript - 如何使用 testcafe 打印 promise 的内部文本?