【问题标题】:What Dart's List's "some" method is called? Method checking if at least one element passes a testDart 的 List 的“some”方法叫什么?检查至少一个元素是否通过测试的方法
【发布时间】:2020-05-19 10:57:45
【问题描述】:

在 JavaScript 数组上,有 some 方法:

some() 方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。它返回一个布尔值。

我认为 Dart 列表中也一定有类似的方法,但我似乎无法在 Internet 或 List docs 的任何地方找到它。

我习惯了 Dart 的某些方法有不同的名称,所以我总是花大约 5 分钟的时间,直到我记得 JavaScript 的 find 被称为 where,等等。但是,我似乎找不到 some 的等价物。

【问题讨论】:

    标签: list flutter dart iterable


    【解决方案1】:

    嗯!问题在于 JavaScript 的 some 方法的等效项是 Iterable class 上的方法,而不是 List 上的方法。 List 类实现了 Iterable,所以我可以早点找到它,但我想我迷失在所有这些方法描述中。

    Dart 等效于 some 方法被调用:any

    Iterable<E> bool any(bool test(E element))

    检查此迭代的任何元素是否满足test

    按迭代顺序检查每个元素,如果其中任何一个使 test 返回 true,则返回 true,否则返回 false。

    示例用法:

    // The list in which we want to check if there is an item that passes a certain test.
    List<String> haystack = [
      // It contains some elements...
    ];
    // Just to be explicit in this example, you don't really need it
    typedef TestFunc = bool Function(String);
    // The test. Just some function that takes an element and returns boolean.
    TestFunc isNeedle = (String v) => v.toLowerCase().contains('needle');
    
    bool gotNeedle = haystack.any(isNeedle);
    

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 2013-12-27
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多