你能想到多少種獲取數組第N個元素的方法?
作為一個前端工程師,數據的處理能力必然是很重要的。對于常見的數組,想要獲取其中的第N個元素,究竟有多少種方法呢?
比如,我們要獲取數組 array 的 第 3 個元素。
- const array = [
- { id: 1, name: 'Mario' },
- { id: 2, name: 'Doom'},
- { id: 3, name: 'Jack'},
- { id: 4, name: 'Yvette'}
- ]
1. for 循環
最簡單的當然是 for / forEach 循環啦。
- let result;
- for (let index = 0; index < array.length; index++) {
- if (index === 2) {
- result = array[index];
- }
- }
2. Array.prototype.forEach
forEach 不用多介紹,相信大家都知道。這里使用 forEach,而不選中 map 的原因很簡單,因為這里不需要返回一個新的數組,甚至也不需要返回值,而且 forEach 還可以中斷。如果是一個超級大大大數組,優勢就出來了。
- let result;
- array.forEach((item, index) => {
- if(index === 2) {
- result = item;
- return;
- }
- });
3. Array.prototype.find
find 和 forEach 應該都是大家比較常用的方法了。find 返回的是數組中第一個滿足條件的元素,用在這里也合適。
- const result = array.find((item,index) => index === 2);
4. Array.prototype.slice
slice 于我而言,沒有 find 和 forEach 用得頻繁。最最最關鍵的是,每次用 slice 之前,我都會把 splice 在心里想一遍去確認,討厭這種超級相近的單詞。
slice 返回的是一個數組,slice(start, end),如果不傳 end 的話,就返回從 start一直到數組末尾。
- const result = array.slice(2,3)[0];
如果 start 是負數的話,那么就會從數組的末尾開始,比如,獲取數組的最后一個數:
- const lastOne = array.slice(-1)[0];
獲取數組的倒數第二個數:
- const lastSecond = array.slice(-2, -1)[0];
如果有人跟我一樣,對 slice 和 splice 這種超級單詞超級像的方法會有點傻傻分不清的話,我是這樣去區分的:
splice 比 slice 多個 p,而 splice 會改變原數組,一般會修改原數組的方法都不是我的首選,所以這個多出來的這個 p 真的就是個 P。
記這些東西真的好難,哈哈哈哈,尤記當年記 “上北下南,左西右東”時,前半句我一直沒有問題,后半句,我總是不分期是“左西右東”,還是“左東右西”,后來,我自己總結了下,封口的要對不封口的,不封口的要對封口的,“左”不封口,所以它要跟一個封口的“西”,“右”是封口的,所以它和“東”在一起,從此之后,我就再也沒有高混過了。
5. Array.prototype.at
數組原型新增的方法,個人認為這是最最最方便的方法了。和 slice 不同,它返回的就是第N個元素。
- const result = array.at(2);
和 slice 類似,如果入參是負數的話,那么將會從數組的末尾開始。
例如,獲取最后一個元素:
- const lastOne = array.at(-1);
獲取倒數第二個元素:
- const lastSecond = array.at(-2);
用它用它用它。
6. lodash 的 nth
如果你項目中使用了 lodash 的話,那么 nth 當然也是一個很好的選擇。
- import { nth } from 'lodash';
- const result = nth(array, 2);