我正在写一本教科书。
问题是:
定义一个函数 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/