簡體   English   中英

dart 模運算符循環列表

[英]dart modulo operator circular list

我想使用模 (%) 運算符以循環方式訪問列表項。 但是下面的代碼不起作用:

void main() {
  List<String> myList = ['one', 'two', 'three', 'four'];
  int currIdx = 0;
  
  for (int i = 0;i < 10;i++) {
    print(myList[currIdx]);
    currIdx = currIdx++ % myList.length;
  }
}

在此處輸入圖像描述

這是解決方案:而不是編碼

currIdx++

你必須編碼

++currIdx

完整代碼:

void main() {
  List<String> myList = ['one', 'two', 'three', 'four'];
  int currIdx = 0;
  
  for (int i = 0;i < 10;i++) {
    print(myList[currIdx]);
    currIdx = ++currIdx % myList.length; // look second comment below which is very useful !
  }
}

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM