Author: knaagar
Translator: Front-end Xiaozhi Source: dev
If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.
find array element
Below are three ways to find an array element from start to end.
method one:
['a', 'b', 'a'].indexOf('a') // 0
['a', 'b', 'a'].indexOf('c') // -1
Method Two:
['a1', 'b', 'a2'].find(x => x.startsWith('a')) // 'a1'
['a1', 'b', 'a2'].find(x => x.startsWith('c')) // undefined
Method three:
['a1', 'b', 'a2'].findIndex(x => x.startsWith('a')) // 0
['a1', 'b', 'a2'].findIndex(x => x.startsWith('c')) // -1
The latest proposal introduces the findLast
and findIndex
methods, which are used as follows:
['a1', 'b', 'a2'].findLast(x => x.startsWith('a')) // 'a2'
['a1', 'b', 'a2'].findLastIndex(x => x.startsWith('a')) // 2
3. Simple implementation
Next, let's simply implement .findLast()
and .findLastIndex()
:
.findLast()
function findLast(arr, callback, thisArg) {
for (let index = arr.length-1; index >= 0; index--) {
const value = arr[index];
if (callback.call(thisArg, value, index, arr)) {
return value;
}
}
return undefined;
}
.findLastIndex()
function findLastIndex(arr, callback, thisArg) {
for (let index = arr.length-1; index >= 0; index--) {
const value = arr[index];
if (callback.call(thisArg, value, index, arr)) {
return index;
}
}
return -1;
}
polyfill
If you want to experience it in advance, you can introduce it in core-js.
Address: https://github.com/tc39/proposal-array-find-from-last#polyfill
The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool , Fundebug .
Original: https://2aliy.com/2022/03/array-find-last.html
comminicate
If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。