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

JavaScript使用for...of循环统计数组中唯一元素出现次数的实现问题

现有代码问题梳理

你的代码存在两处不符合题目要求的问题:

  • 提前写死了n/e/s/w四个方向的固定计数变量,无法适配任意方向值的输入(比如题目示例中的north、south这类自定义方向就无法正常统计)
  • 最终仅打印了计数结果字符串,没有返回题目要求的统计对象
符合要求的实现方案
function loopOverArray(directions) {
  // 按题目要求预先定义空统计对象
  const countResult = {};
  // 用for循环遍历输入数组
  for (let i = 0; i < directions.length; i++) {
    const currentDirection = directions[i];
    // 更新统计值:已存在的方向计数+1,不存在的方向初始化为1
    countResult[currentDirection] = countResult[currentDirection] ? countResult[currentDirection] + 1 : 1;
  }
  // 返回统计对象
  return countResult;
}
测试验证

执行以下测试用例可得到题目要求的输出结果:

console.log(loopOverArray(["n", "s", "e", "e"])); // {n: 1, s: 1, e: 2}
console.log(loopOverArray(["north", "south", "south", "north"])); // {north: 2, south: 2}
console.log(loopOverArray([])); // {}
方案说明
  • 没有固定任何预设方向,支持统计任意输入的方向字符串,覆盖所有题目场景
  • 严格遵循题目要求:使用for循环遍历、初始化空对象存储统计结果、最终返回统计对象
  • 逻辑简洁,没有冗余的多重条件判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:30:02