You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更简便统计数组中连续重复元素?JavaScript代码优化咨询

解决方案

1. 无需转换为字符串的实现方法

可以直接遍历数组,通过索引检查连续三个元素是否为相同的'h'或't',同时保持和你原代码一致的计数逻辑(找到一组后跳过后续两个元素,避免重叠计数):

function repeat(arr) {
    let count = 0;
    let i = 0;
    const len = arr.length;
    while (i <= len - 3) {
        const current = arr[i];
        // 检查连续三个是否为相同的h或t
        if (current === arr[i+1] && current === arr[i+2] && (current === 'h' || current === 't')) {
            count++;
            i += 3; // 跳过已计数的三个元素
        } else {
            i++;
        }
    }
    console.log(count);
}

repeat(["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"]); // 输出3

如果需要支持重叠计数(比如连续4个'h'算2次),只需把i += 3改成i += 1即可。

2. 合并原代码中的两个while循环

可以用正则表达式一次性匹配所有符合条件的子串,替代两次循环:

function repeat(arr) {
    const string = arr.join('');
    // 匹配所有连续的hhh或ttt,返回匹配结果数组
    const matches = string.match(/hhh|ttt/g);
    // 统计数量,无匹配时返回0
    const count = matches ? matches.length : 0;
    console.log(count);
}

repeat(["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"]); // 输出3

这种方式代码更简洁,本质是把两次循环的逻辑交给正则引擎处理,结果和你原代码完全一致。

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:11:35