Dart的List比較特殊的幾個API


List里面常用的屬性和方法:

  • 常用屬性:

length 長度
reversed 翻轉
isEmpty 是否為空
isNotEmpty 是否不為空

  • 常用方法:

add 增加
addAll 拼接數組
indexOf 查找 傳入具體值
remove 刪除 傳入具體值
removeAt 刪除 傳入索引值
fillRange 修改
insert(index,value); 指定位置插入
insertAll(index,list) 指定位置插入List
toList() 其他類型轉換成List
join() List轉換成字符串
split() 字符串轉化成List

 


 

 

上面的這些API在其他語言中也類似。下面列舉幾個比較特殊一點的。

  • foreach

void main() {

  List myList = ["香蕉","蘋果","西瓜"];

  myList.forEach((i) {
    print("$i");
  });
  
}

 

  • map

void main() {

  List oldList = [1,2,3];

  List newList = oldList.map((i) {
    return i * 2;
  }).toList();

  print(newList);

}

// 輸出結果:[2, 4, 6]

 

  • where

void main() {

  List oldList = [1,2,3,4,5,6,7,8,9];

  List newList = oldList.where((i) {
    return i > 5;
  }).toList();

  print(newList);

}

// 輸出結果:
[6, 7, 8, 9]
 
        

 

  • any

void main() {

  List oldList = [1,2,3,4,5,6,7,8,9];

  bool result = oldList.any((i) {  // 只要集合里面有滿足條件的就返回true
    return i > 5;
  });

  print(result);

}

// 輸出結果:true

 

  • every

void main() {

  List oldList = [1,2,3,4,5,6,7,8,9];

  bool result = oldList.every((i) {  // 集合里面每一個都滿足條件時就返回true
    return i > 5;
  });

  print(result);

}

// 輸出結果:false

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM