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

Dart中containsKey()函数为何无法检测重复字符作为键?

问题解决:Dart中Map.containsKey()未正确检测重复字符键

测试字符串'current '时,Map的containsKey()函数未正确识别重复的字符键'r'——本该在已有值2后拼接新索引3,结果直接将'r'的原始值替换成了3。

原代码

void main(){
  Map<String, String> split = new Map();
  var word = 'current ';
  for (int i = 0; i < word.length; i++) {
    String temp = word[i];
    if (split.containsKey([temp])) {
      split[temp] = split[temp]! + ' ' + i.toString();
    } else {
      split[temp] = i.toString();
    }
  }
  print(split.toString());
}

问题分析

核心错误在于containsKey([temp]):这里传入的是List类型参数,但Map的键是String类型,因此永远无法匹配到已存在的String键,每次都会执行else分支,导致重复键的值被覆盖。

修正后的代码

void main(){
  Map<String, String> split = new Map();
  var word = 'current ';
  for (int i = 0; i < word.length; i++) {
    String temp = word[i];
    if (split.containsKey(temp)) { // 移除方括号,直接传入String类型的键
      split[temp] = split[temp]! + ' ' + i.toString();
    } else {
      split[temp] = i.toString();
    }
  }
  print(split.toString());
}

输出结果

修正后输出为:

{c: 0, u: 1, r: 2 3, e: 4, n: 5, t: 6}

与期望输出一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:40:31