在 JavaScript 中编写 indexOf 函数
Writing indexOf function in JavaScript
我是 JavaScript 的新手。我创建了一个 indexof 函数,但它没有给出正确的输出:
问题是:
/*
实现一个名为 indexOf 的函数,它接受两个参数:一个字符串和一个字符,以及 returns 字符在字符串中的第一个索引。
*/
这是我的代码:
function indexOf(string, character) {
let result = string;
let i = 0;
let output = 1;
while (i < result.length) {
if (result[i] === character) {
output = output + indexOf[i];
}
}
return output;
}
我想知道我做错了什么。请帮助。
indexOf() 是一种内置的字符串方法,它告诉您单词中特定字符的索引。请注意,这将始终 return 第一个匹配字符的索引。-
你可以这样写:
function indexOf(string, character){
return string.indexOf(character)
}
所以如果我要使用我的函数并传入两个必需的参数:
indexOf("woof", "o") //this would return 1
你让事情变得比你需要的更难了。如果您想在不调用内置 indexOf()
的情况下执行此操作,我认为这是练习的重点,您只需要在条件匹配时立即从函数中 return
。说明说 "return the first index" — 这是循环中的 i
。
如果你通过循环而没有找到传统的东西 return -1
:
function indexOf(string, character) {
let i=0;
while(i < string.length){
if(string[i] == character){ // yes? just return the index i
return i
}
i++ // no? increase i and move on to next loop iteration
}
return -1; // made it through the loop and without returning. This means no match was found.
}
console.log(indexOf("Mark Was Here", "M"))
console.log(indexOf("Mark Was Here", "W"))
console.log(indexOf("Mark Was Here", "X"))
根据你的问题假设练习是只匹配第一次出现的字符而不是子字符串(连续多个字符),那么最直接的方法是:
const indexOf = (word, character) => {
for (let i = 0; i < word.length; i++) {
if (word[i] === character) {
return i;
}
}
return -1;
}
如果你还需要匹配子字符串,如果你想不通,请在这个答案上发表评论,我会帮助你。
我是 JavaScript 的新手。我创建了一个 indexof 函数,但它没有给出正确的输出: 问题是: /* 实现一个名为 indexOf 的函数,它接受两个参数:一个字符串和一个字符,以及 returns 字符在字符串中的第一个索引。 */
这是我的代码:
function indexOf(string, character) {
let result = string;
let i = 0;
let output = 1;
while (i < result.length) {
if (result[i] === character) {
output = output + indexOf[i];
}
}
return output;
}
我想知道我做错了什么。请帮助。
indexOf() 是一种内置的字符串方法,它告诉您单词中特定字符的索引。请注意,这将始终 return 第一个匹配字符的索引。-
你可以这样写:
function indexOf(string, character){
return string.indexOf(character)
}
所以如果我要使用我的函数并传入两个必需的参数:
indexOf("woof", "o") //this would return 1
你让事情变得比你需要的更难了。如果您想在不调用内置 indexOf()
的情况下执行此操作,我认为这是练习的重点,您只需要在条件匹配时立即从函数中 return
。说明说 "return the first index" — 这是循环中的 i
。
如果你通过循环而没有找到传统的东西 return -1
:
function indexOf(string, character) {
let i=0;
while(i < string.length){
if(string[i] == character){ // yes? just return the index i
return i
}
i++ // no? increase i and move on to next loop iteration
}
return -1; // made it through the loop and without returning. This means no match was found.
}
console.log(indexOf("Mark Was Here", "M"))
console.log(indexOf("Mark Was Here", "W"))
console.log(indexOf("Mark Was Here", "X"))
根据你的问题假设练习是只匹配第一次出现的字符而不是子字符串(连续多个字符),那么最直接的方法是:
const indexOf = (word, character) => {
for (let i = 0; i < word.length; i++) {
if (word[i] === character) {
return i;
}
}
return -1;
}
如果你还需要匹配子字符串,如果你想不通,请在这个答案上发表评论,我会帮助你。