首页 > 解决方案 > 在 JS 的条件语句中使用 META CHARACTERS 不起作用

问题描述

我用这个小代码度过了一段糟糕的时光..

我正在尝试使用正则表达式 - 元字符在“wannabe”数组中查找“Le Guin”,而不必直接在条件语句中键入“Le Guin”,而是通过使用一些元字符......

有趣的是,我昨天尝试了这个并且它有效,但我现在不知道它有什么问题......

for 条件语句中的 "!/[Le *Guin]/" 是在说什么......

请问代码有什么问题

wannabe = ["Le Guin", "Ibrahim", "Ope", "You", "Le Guin", "Now", "Then", "Who", "Le Guin"];

for (a = 0; a < wannabe.length; ++a) {
    if (wannabe[a] == !/[Le*Guin]/) {
        document.write(a + ": " + "This is found at: " + a + "<br>")

        break
    } else {
        document.write(a + ": " + "not yet" + "<br>")
    }
}

标签: javascript

解决方案


wannabe = ["Le Guin", "Ibrahim", "Ope", "You", "Le Guin", "Now", "Then", "Who", "Le Guin"];

for (a = 0; a < wannabe.length; ++a) {
    if ('Le Guin'.match(/[Le*Guin]/)) {
        console.log(a + ": " + "This is found at: " + a + "<br>")
        break
    } else {
        console.log(a + ": " + "not yet" + "<br>")
    }
}

在 js 中实际上有 match() 方法用于在数组中查找字符串以进行正则表达式。

所以用这个

if ('Le Guin'.match(/[Le*Guin]/))


推荐阅读