gpt4 book ai didi

javascript - JavaScript 函数中的 If Else 条件

转载 作者:行者123 更新时间:2023-11-28 15:53:05 24 4
gpt4 key购买 nike

我在条件条件方面遇到问题。我想返回模式在字符串中开始的索引(如果没有找到则返回-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));

拨弄 http://jsfiddle.net/AfDFb/1/

最佳答案

您的代码中有一些输入错误。在第 15 行,您有

}
return (found);
else {

这不是无效的。将其更改为

return (found);
}
else {

还有一个。

if (caseSensitive = false) {

= 用于赋值。比较时需要在if语句中使用==。同样在第 13 行,模式后面有一个额外的 .。删除它。

if (string.indexOf(pattern.) >= 0) {

Your fiddle example

关于javascript - JavaScript 函数中的 If Else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com