在JavaScript中实现Array.prototype.lastIndexOf()函数

JS中的lastIndexOf()函数返回该元素最后一次出现的索引,并将其作为参数传递到数组中(如果存在的话)。如果不存在,该函数将返回-1。

例如-

[3, 5, 3, 6, 6, 7, 4, 3, 2, 1].lastIndexOf(3) would return 7.

我们需要编写一个与现有lastIndexOf()函数具有相同实用程序的JavaScript函数。

然后,我们必须使用刚刚创建的函数覆盖默认的lastIndexOf()函数。我们将简单地从后面进行迭代,直到找到元素并返回其索引。

如果找不到该元素,则返回-1。

示例

以下是代码-

const arr = [3, 5, 3, 6, 6, 7, 4, 3, 2, 1];
Array.prototype.lastIndexOf = function(el){
   for(let i = this.length - 1; i >= 0; i--){
      if(this[i] !== el){
         continue;
      };
      return i;
   };
   return -1;
};
console.log(arr.lastIndexOf(3));

输出结果

这将在控制台中产生以下输出-

7