loops - 获取循环中的项目索引以与存储的索引匹配

标签 loops flutter dart

我有一种情况,如果字符串列表中的字符串与整数列表中的索引匹配(基于字符串列表生成),我想执行操作

下面是一些伪代码,试图阐明我要实现的目标。

List<int> wordIndex = [1,3,5];
List<String> wordList = ['this', 'is','a', 'test', 'a'];

//Pseudo code
wordList.forEach(word)) {
 if (wordIndex item matches index of word) {
    do something;
  } else {
    od something else;
 }
}

这是我遇到问题的if (wordIndex item matches index of word),不胜感激任何想法。

最佳答案

如果我对您的理解正确,那么您想知道wordIndex列表中是否包含单词的索引,即要获取所有wordList项,并将其索引存储在wordIndex中。

有两种解决方法:

使用 Iterable.contains

在这种情况下,我们可以简单地检查wordIndex列表中是否存在当前索引。

for (var index = 0; index < wordList.length; index++) {
  if (wordIndex.contains(index)) {
    // do something
    return;
  }

  // do something else
}

遍历wordIndex
如果您只对匹配项感兴趣,则此方法更合理。
在这里,我们遍历索引列表,然后简单地在wordList中获取匹配的元素。但是,您将无法对不匹配的商品采取措施:

for (final index in wordIndex) {
  final word = wordList[index];

  // do something
}

关于loops - 获取循环中的项目索引以与存储的索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61431937/

相关文章:

c - 打印号码

firebase - Flutter 和 Firestore 在请求中没有用户信息

angular - *ngFor 不能在 dart angular(4) 中工作

flutter - [SOLVED]更新错误:成功发送HTTP发布后,我在Microsoft SQL Server中的数据没有更改(200)

asp.net - http到https重写了太多的重定向循环IIS 7

python - 让 Pygame 播放一次声音

bash - While 循环重置 Bash 脚本中的数字变量

json - Dart/Flutter - 比较两个 List<object> 检查它们是否具有相同的值

flutter - 又抛出异常: Multiple widgets used the same GlobalKey

string - Dart String 可迭代接口(interface)