如何使forEach循环按index字段值升序调用otherFunc函数?
解决方案
你需要先对fields数组按照index字段从小到大排序,再执行遍历调用otherFunc,这样就能保证调用顺序符合预期。
修改后的代码示例:
const func2 = (result) => { // 按index升序排序后遍历,若不想修改原数组,可改用 [...result.data.fields] 复制一份再排序 result.data.fields.sort((a, b) => a.index - b.index).forEach((d) => { otherFunc(d.label); }); }; const otherFunc = (d) => { // 执行你的业务逻辑 };
关键说明:
Array.sort((a, b) => a.index - b.index)会按index数值从小到大排序数组:当a.index小于b.index时返回负数,a排在b前面;相等时返回0,顺序不变;大于时返回正数,b排在a前面。- 如果不想改变原数组的原始顺序,优先创建数组副本再排序,避免影响其他依赖原数组顺序的逻辑,示例代码:
[...result.data.fields].sort((a, b) => a.index - b.index).forEach((d) => { otherFunc(d.label); });
内容的提问来源于stack exchange,提问作者nb_nb_nb
相关产品推荐
相关产品推荐

