如何检测分块数组中最后一个分块的最后一个元素索引
解决方法
有几种简单的方式可以实现这个需求:
方法一:利用数组索引判断
在嵌套的forEach循环中,通过外层索引判断当前是否为最后一个分块,同时通过内层索引判断当前是否为该分块的最后一个元素:
import { chunk } from 'lodash'; const chunked = chunk([1, 2, 3, 4, 5, 6], 2); // [[1,2], [3,4], [5,6]] chunked.forEach((c, i) => { c.forEach((e, index) => { // 判断是否是最后一个分块的最后一个元素 if (i === chunked.length - 1 && index === c.length - 1) { something(); } }) })
方法二:提前获取最后一个分块信息
可以提前取出最后一个分块,避免循环中重复计算数组长度,判断逻辑更直观:
import { chunk } from 'lodash'; const chunked = chunk([1, 2, 3, 4, 5, 6], 2); const lastChunk = chunked[chunked.length - 1]; chunked.forEach((c, i) => { c.forEach((e, index) => { if (c === lastChunk && index === lastChunk.length - 1) { something(); } }) })
方法三:直接定位最后一个元素(无需遍历全部元素)
如果你的需求仅需触发最后一个元素的处理逻辑,不需要遍历前面的元素,可以直接跳过循环,定位到目标元素后执行函数:
import { chunk } from 'lodash'; const chunked = chunk([1, 2, 3, 4, 5, 6], 2); const lastElement = chunked[chunked.length - 1][chunked[chunked.length - 1].length - 1]; something(lastElement);
内容的提问来源于stack exchange,提问作者Taylor Foster
相关产品推荐
相关产品推荐

