3 回答
TA贡献1815条经验 获得超6个赞
您不需要Array.indexOf()找到当前角色。由于i是当前字符的索引,用它从字符串中取出当前字符,并与目标进行比较。最后返回count。
注意:returnJS 中的语句不能返回两个项。如果您使用逗号分隔的列表 -target, input例如 - 最后一项将被返回。
function countCharacters(target, input) {
var count = 0;
for (var i = 0; i < input.length; i = i + 1) {
if (input[i] === target) { //if a character in the string matches the target character
count = count + 1;
}
}
return count;
}
console.log(countCharacters("s", "Mississippi"));
TA贡献1864条经验 获得超2个赞
在这里,您正在与索引和目标进行比较。你应该得到当前字符然后比较。正如我在下面所做的那样,它可能会帮助您...
function countCharacters(target, input) { //Defining of the function, the parameters are target and input
var count = 0; //set count to 0 before the for loop
for (var i = 0; i < input.length; i = i + 1) { //the for loop that goes through each index of the input string
if (input[i] == target) { //if a character in the string matches the target character
count = count + 1; //count adds 1 to its value
}
}
console.log(count); //When it breaks out of the loop, the amount of times the target was matched will be printed
return target, input; //return two parameters
}
console.log(countCharacters("s", "Mississippi"));
TA贡献1830条经验 获得超9个赞
事情是这样的:您尝试通过 indexOf() 访问字母 - 最好通过索引访问它,而且函数必须只返回一件事,而您的则返回两件事
function countCharacters(target, input) {
let count = 0;
for (let i = 0; i < input.length; i++) {
if (input[i] === target) {
count++;
}
}
return count;
}
console.log(countCharacters("s", "Mississippi"));
添加回答
举报