定义函数lastIndexOf?

时间:2018-08-11 22:29:07

标签: javascript arrays lastindexof

我正在写教科书。

这是问题:

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

然后尝试以下功能:

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

我知道有一个lastindexof()方法。我只是不知道如何在此功能中实现它。

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

我是一名新手学生,但是根据您的经验编程,您将如何考虑这样做?您的思考过程如何?我应该知道些什么?

5 个答案:

答案 0 :(得分:1)

只要找到最后一个元素,就从最后一个元素开始返回。

最后一个索引为array.length - 1。使用经典的for循环。

祝你学习顺利!

答案 1 :(得分:1)

  1. 从最后一个元素(长度为1)的索引处开始。
  2. 如果索引<0,则返回-1
  3. 将索引处的元素与“ needle”进行比较
  4. 如果匹配,则返回索引
  5. 减少索引并从#2开始重复

我会给你一个片段,但这会使它变得很容易:)

答案 2 :(得分:1)

有很多方法可以实现它。

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


我要写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);


P.S。对于非常大的数组,这三种方法可能不太理想,因为您无法预测所要查找的值接近数组的结尾或开头。

因此,在这种情况下,您可以从二叉树算法中获得启发。

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

答案 3 :(得分:1)

Array.prototype.lastIndexOf()的工作方式如下:

var arr = [ 0, 1, 4, 1, 2 ];

console.log(arr.lastIndexOf(1));//<-- we look for 1
console.log(arr.lastIndexOf(5));//<-- we look for 5
//or
console.log([ 0, 1, 4, 1, 2 ].lastIndexOf(1));

答案 4 :(得分:1)

已经有一个函数可以执行以下操作:

lastIndexOf()

但这是可以自己实现的方法:

function lastIndex(arr, value) {
  let index = -1;

  for(let i=0; i < arr.length; i++) {
    if(arr[i] === value) {
      index = i;
    }
  }
  return index;
}

console.log(lastIndex([1,2,3,3,3,4], 3))