繁体   English   中英

为什么这个 for 循环会在数组中循环 4 次?

[英]Why is this for loop looping through the array 4 times?

我正在针对某些字符测试数组,我想知道为什么它会循环遍历数组 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/

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM