【问题标题】:Why is this for loop looping through the array 4 times?为什么这个 for 循环遍历数组 4 次?
【发布时间】:2015-11-04 08:21:55
【问题描述】:

我正在针对某些字符测试一个数组,我想知道为什么它会在数组中循环 4 次。我只是想循环一次toTest。这是代码和小提琴

var testAgainst = ['and','+',',','&'];
var toTest = ["$ Red Arcane Playing Cards Deck Ellusionist Rare New Sealed $", "Ellusionist Red Arcane Deck - Very Rare - Playing Cards - Magic Tricks- New", "24 HR Sale! Red and White LTD & Red Arcane Playing Cards Ellusionist near mint", "4x Arcane Playing Cards Deck Collection Rare Gold Red + Black White Ellusionist", "Red Arcane Playing Cards by Ellusionist", "24 HR SALE Red Arcane Playing Cards by Ellusionist", "RED ARCANE PLAYING CARDS", "Ellusionist - New/Sealed Red Arcane Playing cards c.2013 - Rare deck"];

for(var i = 0; i < testAgainst.length; i++){
    for(var j = 0; j < toTest.length; j++){
        if (toTest[j].indexOf(testAgainst[i]) > -1){
            console.log('match: ' + toTest[j]);
        }else{
            console.log('no match ' + toTest[j]);
        }
    }
}

小提琴:https://jsfiddle.net/bmpgsxb2/4/

为什么循环这么多?

感谢所有为我指明正确方向的人。我应该意识到这是怎么回事。在玩了一段时间后,我想出了这个,它只过滤一次数据并根据它是否符合标准来拆分数据

JSFIDDLE 更新: https://jsfiddle.net/bmpgsxb2/7/

【问题讨论】:

  • 你没有忘记代码中的 break 语句吗?
  • 因为 testAgainst 里面有 4 个项目?
  • 因为您有两个嵌套循环,并且您循环 toTest 的次数与 testAgain 中的项目一样多...!?
  • 您正在循环通过 testAgainst。对于 testAgainst 中的每个元素,您将通过 toTest 进行完整的循环。
  • 当你交换两个“for”语句时可能会更清楚

标签: javascript arrays loops


【解决方案1】:

您已经从testAgainsttestAgainst.length === 4 编写了一个for 循环,这就是它在toTest 上循环4 次的原因

你的算法很好。我没有看到任何其他可能性,也许是使用正则表达式,但这取决于你想做什么

【讨论】:

    【解决方案2】:

    您的循环位于另一个循环中,该循环运行 testAgainst.length 次(即 4 次)。

    for(var i = 0; i < testAgainst.length; i++){
        for(var j = 0; j < toTest.length; j++){
    

    【讨论】:

      【解决方案3】:

      您显然在迭代 testAgainst.length * toTest.length 次,即 4 * 8 次 = 32。

      【讨论】:

        【解决方案4】:

        你的算法很好,当你运行外循环 toTest.length 和内循环到 testAgainst.length 时,它可以更优化,这样一旦找到 testAgainst 关键字,然后找到匹配,不需要更多迭代,也放break if 循环中的语句。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-22
          • 2021-09-17
          • 2015-11-25
          • 2017-09-12
          相关资源
          最近更新 更多