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

遍历姓名数组时相邻元素对比异常:仅匹配单个字符的问题排查

问题解决:数组元素与前一个元素对比错误修正

你的代码核心问题是混淆了字符串索引和数组索引:你在对比时用了name[i-1],这里的name是当前遍历到的字符串(比如"Bruce Banner"),所以name[i-1]会取这个字符串的第i-1个字符,而不是数组里的前一个姓名元素,这就是为什么结果里出现了"B"、"r"这类单个字符。

修正后的代码

var nameArray = ["Tony Stark", "Bruce Banner", "Bruce Banner", "Steve Rogers", "Steve Rogers"]
var nameComparisonArray = []
var element = ""

for (let index = 0; index < nameArray.length; index++) {
  const currentName = nameArray[index]
  const previousName = nameArray[index - 1] // 取数组的前一个元素,而非当前字符串的字符

  if (currentName !== previousName) {
    element = `${currentName} is different from ${previousName}`
  } else {
    element = `${currentName} is the same as ${previousName}`
  }
  nameComparisonArray.push(element)
}
console.log("nameComparisonArray", nameComparisonArray)

关键改动说明

  1. 替换索引来源:把name[i-1]改为nameArray[index-1],nameArray是存储所有姓名的原数组,index-1指向数组中当前元素的前一个元素,这才是你需要对比的对象。
  2. 优化代码可读性:用ES6模板字符串`${}`替代繁琐的字符串拼接,同时将变量名改为currentName和previousName,语义更清晰。

运行结果

执行后会得到你预期的输出:

[
  "Tony Stark is different from undefined",
  "Bruce Banner is different from Tony Stark",
  "Bruce Banner is the same as Bruce Banner",
  "Steve Rogers is different from Bruce Banner",
  "Steve Rogers is the same as Steve Rogers"
]

可选优化(按需使用)

如果想把第一个元素的undefined改成更友好的提示(比如"no previous name"),可以添加判断:

const previousName = index === 0 ? "no previous name" : nameArray[index - 1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:57:31