【问题标题】:The end of my for loop is not running in my javascript function我的 for 循环的结尾没有在我的 javascript 函数中运行
【发布时间】: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


【解决方案1】:

你已经接近了。将 return -1; 语句移到 if/else 块之外。正如它目前所写的那样,如果它没有找到匹配的,你只会收到 -1 你传入两个参数。

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;
            }
        }
    }
    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

通过此更改,无论传入的参数数量如何,如果没有匹配项,您将始终点击 return -1;

【讨论】:

    【解决方案2】:

    在最后一个测试用例中,您没有向函数发送第二个参数,因此它将运行 if-else 的第一部分 - if 部分。那部分没有return -1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2021-06-29
      相关资源
      最近更新 更多