gpt4 book ai didi

javascript - JS中是否有相当于 "Array.None"的东西?

转载 作者:行者123 更新时间:2023-12-03 22:46:34 31 4
gpt4 key购买 nike

LINQ 有一个类似的问题:Is there an equivalent of None() in LINQ?
集合/数组上有一些 bool 方法:

  • Array.some (类似于 linq.Any )
  • Array.every (类似于 linq.All )

  • 我可以检查数组中是否没有元素与给定的函数回调匹配吗
    一个可能的解决方法是 .filter然后检查 .length并确保它为零:
    let arr = ["a","b","c"]
    // make sure that no item in array = "b"
    let noBs = arr.filter(el => el === "b").length === 0

    最佳答案

    正如 linq 示例在逻辑上得出的结论

    None is the same as !Any, so you could define your own extension method as follows:


    let none = (arr, callback) => !arr.some(callback)
    然后像这样调用:
    let arr = ["a","b","c"]
    let noBs = none(arr, el => el === "b")

    或者如果你想 extend Array.proto ,可以添加以下方法:
    Object.defineProperty(Array.prototype, 'none', {
    value: function (callback) { return !this.some(callback) }
    });
    然后像这样调用:
    let arr = ["a","b","c"]
    let noBs = arr.none(el => el === "b")

    关于javascript - JS中是否有相当于 "Array.None"的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62906597/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com