javascript - 在 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>")
}
}
解决方案
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]/))
推荐阅读
- c# - ASP.Net MVC:如何使用 2 个参数配置动作路由?
- sql - 在等号的左侧使用日期函数
- ajax - 使用 Postman 时 Laravel 无法将 Request 识别为 Ajax
- python - 如何让 read_html 循环?Python
- python - python检查两个值是否在两个值之间
- java - [Netbeans 8.2] 使用 IKVM 转换我的 .jar 文件时出错
- processing - “,”上的错误考虑添加“表达式”
- java - 每个项目的 Android Studio 3.6.3 构建都失败,没有任何错误
- c - 列表编译,但给出警告:不兼容的指针类型
- python - Python加入csv的最后两个元素