搜索
javascript - 如何优雅地交替遍历两个数组?
phpcn_u1582
phpcn_u1582 2017-05-19 10:41:15
[JavaScript讨论组]

限制语言:Javascript

比如,一个商品列表中会插进几个活动的坑位。

比如,现有 A B 两个数组,长度不定,要6个A数组元素+1个B数组元素这样排列下去

比如,甚至更多个数组交替排列

能想到的就是类似分页一样,把这几个数组变二维数组,然后再用循环把它们组合到一个数组,最后遍历。

有没有更好的办法

phpcn_u1582
phpcn_u1582

全部回复(2)
phpcn_u1582
var a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5],
    b = [11,22,33,44,55];
    
a.reduce((acc,ele,idx) => ((idx + 1) % 3 ? acc.push(ele) : acc.push(ele, b.shift()), acc), []);

优雅么。。。

巴扎黑
export function join<T>(first: T[], second: T[], firstSize: number, secondSize: number): T[] {
    let out: T[] = []
    let i = 0
    for (; firstSize * i < first.length && secondSize * i < second.length; i++) {
        out = out.concat(
            first.slice(firstSize * i, firstSize),
            second.slice(secondSize * i, secondSize),
        )
    }
    out = out.concat(first.slice(firstSize * i), second.slice(secondSize * i))
    return out
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号