代码之家  ›  专栏  ›  技术社区  ›  Vince Varga

Dart列表的“some”方法调用了什么?方法检查是否至少有一个元素通过测试

  •  0
  • Vince Varga  · 技术社区  · 6 年前

    在JavaScript数组上,有 some 方法:

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

    我认为Dart列表上也有类似的方法,但我似乎在互联网上或 List docs 。

    我习惯于对一些方法使用不同的名称,所以我总是花大约5分钟的时间,直到我记住JavaScript的 find 被称为 where 等等然而,我似乎找不到 一些 的等效项。

    1 回复  |  直到 6 年前
        1
  •  7
  •   Vince Varga    6 年前

    哼!问题是 some 方法是 Iterable class 而不是在 List 这个 列表 类实现 可迭代的 ,尽管如此,我本可以更早地找到它,但我想我在所有这些方法描述中迷失了方向。

    Dart等效于 一些 方法被调用: any :

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

    检查此iterable的任何元素是否满足 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);