javascript - 定义函数 lastIndexOf?

标签 javascript arrays lastindexof

我正在写一本教科书。

问题是:

定义一个函数 lastIndexOf,给定一个数组和一个值,返回该值最后一次出现在数组中的索引。如果该值从未出现,则该函数应返回 -1。

然后在以下方面尝试您的功能:

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

我知道有一个 lastindexof() 方法。我只是不知道如何在这个函数中实现它。

我的问题是,我应该如何解决这个问题?

我是一名新手,但以您的编程经验,您会如何考虑这样做呢?你的思考过程是什么?我应该知道什么?

最佳答案

有很多方法可以实现它。

一切都取决于您的“创造力”。


我会写其中的 3 个:

1) 直接循环直到最后一场比赛:

const lastIndexOf = (haystack, needle) => {
  let index = -1;
  haystack.forEach(function(element, i) {
    if (element === needle) index = i;
  });
  return index;
}


let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']

console.log('Index of:', fruits.indexOf('mango')); 
console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
console.log('Last Index of:', lastIndexOf(fruits, 'potato'));

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

2) 使用 -1 step 循环并在第一次匹配时停止:

const lastIndexOf = (haystack, needle) => {
  for (let i = haystack.length -1; i >= 0; i--) {
    if (haystack[i] === needle) return i;
  }
  return -1;
}


let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']

console.log('Index of:', fruits.indexOf('mango')); 
console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
console.log('Last Index of:', lastIndexOf(fruits, 'potato'));

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

3)反向排序+“长度数学”:

const lastIndexOf = (haystack, needle) => {
  const rIndex = haystack.reverse().indexOf(needle);
  return (rIndex > -1) ? haystack.length - rIndex - 1 : -1;
}


let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']

console.log('Index of:', fruits.indexOf('mango')); 
console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
console.log('Last Index of:', lastIndexOf(fruits, 'potato'));

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);


附言在非常大的数组的情况下,这 3 种方法可能不太理想,因为您无法预测您正在寻找的值接近数组的结尾或开头。

所以对于这种情况可以从二叉树算法中得到启发。

一切都取决于任务的复杂性。

关于javascript - 定义函数 lastIndexOf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804254/

相关文章:

c - 映射枚举和字符串

ruby - 如何获取与某个正则表达式匹配的数组中元素的位置?

java - 使用 Jackson 进行反序列化 : "org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of [projectname]."

javascript - AngularJS $routeprovider 在 Mutitab 中路由

javascript - 根据长度过滤和排序字符串数组?

list - 如果它是列表的最后一个索引,如何返回一个小部件?

c++ - boost::算法::字符串::finder.hpp

c# - String.Contains 和 String.LastIndexOf C# 返回不同的结果?

javascript - 单个变量行在javascript中意味着什么?

javascript - createElement 和伪类