0

数组以 [] 开头,然后随着添加的数字不断增长。

我正在尝试创建一个选择器来提取数组的最后两个元素。

我有以下内容:

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)
        );
4

1 回答 1

15

您可以使用负开始索引从末尾开始切片。文档

可以使用负索引,表示距序列末尾的偏移量。slice(-2) 提取序列中的最后两个元素。

['zero', 'one', 'two', 'three'].slice(-2)
//["two", "three"]
于 2017-04-15T19:03:58.383 回答