1

我正在写一本教科书。

这是问题:

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

然后在尝试以下功能后:

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

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

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

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

4

5 回答 5

1

只需从最后一个元素开始,如果你找到你要找的东西就返回。

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

祝你学习顺利!

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

我会给你一个片段,但这太容易了:)

于 2018-08-11T22:32:59.117 回答
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);


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

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

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

于 2018-08-11T22:35:53.543 回答
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));

于 2018-08-11T22:41:58.653 回答
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))

于 2018-08-11T22:43:04.687 回答