2 回答

TA贡献1775条经验 获得超8个赞
问题出在你的 if 语句中,你正在比较 indexOf 的结果是否为 === -1,但如果 indexOf 函数返回 -1 则意味着未找到子字符串,因为他在你的字符串中找到“ninja”它不执行代码而是跳转到 else。
它应该是:
if (myString.indexOf("ninja") != -1){
console.log ("The word ninja starts at position " + myString.indexOf("ninja"));
} else {
console.log ("The word ninja is not in the string");
}

TA贡献1943条经验 获得超7个赞
这会给你想要的结果。2件事情要注意:
该字符串是使用单引号构建的,因此其中的任何单引号都需要使用反斜杠进行转义
\
声明中的比较
if
是错误的。您应该检查索引是否不是 -1,这意味着该字符串确实存在。
var myString = 'I\'m a "fun ninja" string';
if (myString.indexOf("ninja") !== -1) {
console.log ("The word ninja starts at position " + myString.indexOf("ninja"));
} else {
console.log ("The word ninja is not in the string");
}
添加回答
举报