javascript - indexOf 的简单算法在 JS 中不起作用
问题描述
我的任务是查找并输出输入的标签/单词在句子中的位置。控制台给了我那个地方 var 没有定义。我应该怎么办?非常感谢!
var sentence = prompt("Enter you sentence");
var word = prompt("Enter the tabs/word you looking for");
var counter = 0;
var place = stntence.indexOf(word, counter);
if (stntence.indexOf(word) != -1) {
while (place != -1) {
if (place != -1) {
console.log("The place of the word/tab is: " + place);
counter = place++;
} else {
console.log("That's all")
}
}
} else {
console.log("the word/tabs are not exist in the sentence");
}
解决方案
除了 的错字stntence !== sentence
,您可以利用计数器并通过直接在while
条件中分配位置来使用缩短的方法。
var sentence = prompt("Enter you sentence"),
word = prompt("Enter the tabs/word you looking for"),
counter = 0,
place = -1;
while ((place = sentence.indexOf(word, place + 1)) != -1) {
console.log("The place of the word/tab is: " + place);
counter++;
}
if (counter) {
console.log("That's all");
} else {
console.log("the word/tabs are not exist in the sentence");
}
推荐阅读
- scala - 在scala中将元组与布尔值进行大小写匹配的有效方法
- angular - Angular Material 自定义组件主题 - 包大小优化
- sql - 如果存在则需要更新或插入值
- windows - 如何在文件夹的每个子目录中执行命令?
- security - com.ibm.websphere.crypto.KeyGenerator 在 WebSphere 中的实现应该放在哪里?
- websocket - SignalR:使用 Nginx 出现错误 400 的 Web 套接字握手问题
- node.js - 解析仪表板问题 - 表单被篡改
- python - 如何在 Windows 10 中使用 pip 安装 tkinter
- bootstrap-4 - 如何使用引导程序垂直居中
- python - 从 pandas 中的 JSON 列中提取属于特定键的值