2017-04-15 83 views
0

數組從[]開始,然後隨着數字添加到數組中而不斷增長。獲取選擇器中數組的最後2個元素(Redux)

我想創建一個選擇器來提取數組的最後2個元素。

我有以下幾點:

const getHistory = (state) => state.score.history; 

export const lastTwo = createSelector(
    [getHistory], 
    history => (history.length > 1 ? history.slice(-1, -3) : 0) 
); 

它顯示了最初的0,但隨後不輸出任何價值。請指教。如果只是爲了測試目的,我這樣做:

export const lastTwo = createSelector(
     [getHistory], 
     history => history 
    ); 

它正確地輸出數組元素,因爲它們被添加。

編輯:

基於下面的答案,答案是:

export const lastTwo = createSelector(
      [getHistory], 
      history => history.slice(-2) 
     ); 
+2

'history.slice(-2)'前提是'history'是'Array'。 –

+0

謝謝 - 我總是試圖不必要地使事情複雜化。 – Wasteland

回答

2

您可以使用排除開始指數結束切片。 Docs

可以使用負指數,指示從 序列末尾的偏移量。切片(-2)提取序列中的最後兩個元素。

['zero', 'one', 'two', 'three'].slice(-2) 
//["two", "three"]