【问题标题】:check if items in array existed and add new values from another array without overwriting?检查数组中的项目是否存在并从另一个数组添加新值而不覆盖?
【发布时间】:2022-11-18 19:10:56
【问题描述】:

我想检查数组中的项目是否存在,并在重新加载后不覆盖元素的情况下从另一个数组添加新值。我创建了这样的代码:

//take from that array
    List<int> list = [2, 3, 5];
  // add to this array and check if this array already has the same element or not    
      List<int> newValueInt = [2, 6, 7];
    
      list.forEach((item) {
        if(!list.contains(item)){
          newValueInt.add(item);
          print(newValueInt);
        }  
      });

它告诉我打印:

     [2, 6, 7, 3]
[2, 6, 7, 3, 5]

【问题讨论】:

  • !list.contains(item) 始终为 false,因为您正在调用 list.forEach

标签: flutter dart


【解决方案1】:
if(!list.contains(item)){

if(! newValueInt.contains(item)){

【讨论】:

    【解决方案2】:
    List<int> list = [2, 3, 5];
      // add to this array and check if this array already has the same element or not
      List<int> newValueInt = [2, 6, 7];
      List<int> temp = [];
      for (var item in list) {
        if(!newValueInt.contains(item)){
          temp.add(item);
        }
      }
    
      List<int> result = newValueInt + temp;
    
      print(result); //---> [2, 6, 7, 3, 5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多