找到存在值的第一个索引

问题描述:

我正在尝试遵循以下说明:

I am trying to follow these instructions:

编写一个名为indexOf的函数,该函数接受一个数组和一个数字。

"Write a function called indexOf, which accepts an array and a number.

该函数应该返回该值所在的第一个索引;如果找不到该值,则返回-1。

The function should return the first index at which the value exists or -1 if the value is not found.

请勿使用内置数组.indexOf()函数!

Do not use the built in Array.indexOf() function!"

这是我所拥有的:

function indexOf(arr, number) {
  var panda = arr.indexOf(number) || -1;
  if(typeof(arr) == "object"){
            return arr.indexOf(number);
        } else {
          return -1;
}
}
console.log(
  indexOf([1, 2, 3, 4], 7),
  indexOf([1, 2, 3, 4], 3)
  );

$ p
$ b

我正在处理repl.it上的一些问题,因此控制台中的输出是正确的,但我仍然无法通过repl.it进行测试。有人可以帮我解决我做错的事情吗?我已经通过几种不同的方式进行了研究,但是我不确定使用typeof是评估数组中是否确实存在给定数字的最佳方法,但是同时又对如何评估它是否存在感到困惑而不使用Array.indexOf函数。

I am working through some problems on repl.it, so my output in the console is correct, but I am still failing the test cases on repl.it. Could someone help me work through what I am doing wrong? I have gone about this a couple of different ways, but I am not sure using typeof is the best way to evaluate whether or not a given number actually exists in an array, but at the same time and confused on how to evaluate if it exists without using the Array.indexOf function.

您不能使用 .indexOf(),所以我'm假设您可以使用 .findIndex()

You can't use .indexOf(), so I'm assuming you can use .findIndex()?

function indexOf(arr, number) {
  return arr.findIndex(n => n === number);
}
console.log(
  indexOf([1, 2, 3, 4], 7),
  indexOf([1, 2, 3, 4], 3)
);