数组以 [] 开头,然后随着数字的添加而不断增长。
我正在尝试创建一个选择器来提取数组的最后 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)
);
最佳答案
您可以使用负开始索引从末尾开始切片。 Docs .
A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
['zero', 'one', 'two', 'three'].slice(-2)
//["two", "three"]
关于javascript - 获取选择器中数组的最后 2 个元素 (Redux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43430006/