作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在条件条件方面遇到问题。我想返回模式在字符串中开始的索引(如果没有找到则返回-1)。如果第三个参数为 true,则搜索区分大小写,否则不区分大小写。
Examples
index("abAB12","AB",true) returns 2 but index("abAB12","AB",false) returns 0
index("abAB12","BA",true) returns -1 and index("abAB12","BA",false) returns 1
知道如何实现这个目标吗?
这是我到目前为止的代码
var s = "abAB12"
var p = "AB"
var cs = true
function index(string, pattern, caseSensitive) {
if (pattern) {
var found = false;
if (caseSensitive = false) {
if (string.indexOf(pattern.) >= 0) {
found = true;
}
return (found);
else {
return ("");
}
} else if (caseSensitive = true) {
if (string.toLowerCase().indexOf(pattern.toLowerCase()) >= 0) {
found = true;
}
return (found);
} else {
return ("");
}
}
}
alert(index(s, p, cs));
最佳答案
您的代码中有一些输入错误。在第 15 行,您有
}
return (found);
else {
这不是无效的。将其更改为
return (found);
}
else {
还有一个。
if (caseSensitive = false) {
=
用于赋值。比较时需要在if语句中使用==
。同样在第 13 行,模式后面有一个额外的 .
。删除它。
if (string.indexOf(pattern.) >= 0) {
关于javascript - JavaScript 函数中的 If Else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877678/
我是一名优秀的程序员,十分优秀!