【发布时间】:2021-10-07 20:44:32
【问题描述】:
我正在尝试在 JavaScript 中重新创建 indexOf 函数。我无法让 return -1 部分工作,但其他部分工作正常。当我尝试打印出“循环结束”时,似乎我的 for 循环的结尾没有运行。我也有一些测试代码和下面的输出。任何帮助将不胜感激。
Array.prototype.myIndexOf = function(...args) {
if(args[1] === undefined){
for(let i = 0; i < this.length; i++){
if(this[i] === args[0]){
return i;
}
}
} else {
for(let i = args[1]; i < this.length; i++){
if(this[i] === args[0]){
return i;
}
}
console.log("end of loop")
return -1;
}
};
// TEST
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
console.log(beasts.myIndexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
console.log(beasts.myIndexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
console.log(beasts.myIndexOf('giraffe'));
// expected output: -1
1
1
4
4
-1
undefined
【问题讨论】:
-
虽然很多人已经把答案交给了你,但我还是鼓励你自己去弄清楚。在调试器中单步调试代码,或用铅笔和纸“玩电脑”:在您的脑海中遍历代码并弄清楚实际发生了什么。仅缩进就足以为您指明正确的方向:在第一个条件下会发生什么?当
for循环结束时会发生什么?控制去哪儿了?
标签: javascript indexof