【问题标题】:How to find if a value is in nested arrays [closed]如何查找值是否在嵌套数组中[关闭]
【发布时间】:2020-05-18 13:54:21
【问题描述】:

var array = [["1", "2], ["3", "4"], ["5", "6"]]

我想看看变量中是否有数字“4”

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。
  • @T.J.Crowder 你是什么意思?
  • 你应该展示你为解决问题所做的努力。

标签: javascript arrays node.js


【解决方案1】:

您可以使用Array.prototype.flat()Array.prototype.includes()

const array = [["1", "2"], ["3", "4"], ["5", "6"]],

      result = array.flat().includes('4')
      
console.log(result)      

上面很容易调整(通过将flattening深度作为参数传递给flat())到几乎任何嵌套深度。

如果这只是 2 个级别的深度,您可能会选择Array.prototype.some()Array.prototype.includes() 的性能更高的组合:

const array = [["1", "2"], ["3", "4"], ["5", "6"]],

      result = array.some(a => a.includes('4'))
      
console.log(result)

【讨论】:

    【解决方案2】:
    const array = [["1", "2"], ["3", "4"], ["5", "6"]];
    const value = '4';
    /*
     * const result = (new RegExp(value,'gi')).test(array.join()) 
     * result will be true for `4` , `44` , `444` ...
     */
    
    /*
     * to get the exact match we have to use word boundary
     */
    const result = (new RegExp(`\\b${value}\\b`,'g')).test(array.join())
    

    Word boundary: \b

    【讨论】:

    • 当没有'4',但'44' 存在时,您的代码将返回意外结果。
    • 谢谢@YevgenGorbunkov ,我必须添加单词边界。
    【解决方案3】:
    function CheckNumberInArray(array, number) {
        FoundNumber = False;
        for (var i = 0; i < array.length; i++) {
            for (var j=0; j < array[i].length;j++) {
              if (array[i][j] == number) {
                  FoundNumber = true;   // Found it
              }
            }
        }
        return FoundNumber;   // Not found
    }
    

    【讨论】:

    • 您的代码有 2 个语法错误:false 中的大写“F”和 if( 语句正文缺少右花括号
    • ...此外,出于性能考虑(证明这种冗长级别合理的唯一原因),我将摆脱 FoundNumber 变量并在 if( body 和 return false 内执行 return true否则。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2019-08-15
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多