将数组与嵌套循环进行比较

时间:2013-07-06 12:25:15

标签: javascript arrays

我试图将两个数组的值相互比较。如果找到匹配 - 做某事 - 否则这样做。

我在http://jsfiddle.net/ZvmHx/1/

将我的代码放在一起

如果您在第14行取消注释第二个警报,您将看到错误。我似乎无法防止第二次警报被解雇。

谢谢!

var getkeywords = ["John","Frank","Sarah"]; 
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];    

for (k = 0; k < getkeywords.length; k++) {
    for (l = 0; l < captionarray.length; l++) {

    if(getkeywords[k] == captionarray[l]){

        alert('Found > ' + getkeywords[k] + ':filter image');

    }else{

        //alert('not found > ' + getkeywords[k] + ':filter image');

    }
  }
}

3 个答案:

答案 0 :(得分:2)

if / else正在测试内循环的每次迭代。我认为你所追求的是在内部循环运行之后你是否匹配。类似的东西:

var getkeywords = ["John","Frank","Sarah"]; 
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];    
var matchFound;

for (k = 0; k < getkeywords.length; k++) {
    matchFound = false;

    for (l = 0; l < captionarray.length; l++) {
        if (getkeywords[k] == captionarray[l]){
            matchFound = true;
            break;
        }
    }

    if(matchFound){

        alert('Found > ' + getkeywords[k] + ':filter image');

    }else{

        alert('not found > ' + getkeywords[k] + ':filter image');

    }
}

答案 1 :(得分:0)

我创造了一个新的小提琴: -

http://jsfiddle.net/WZGyy/

var getkeywords = ["John","Frank","Sarah"]; 
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];    

imagecode = '';
var found=0;
for (k = 0; k < getkeywords.length; k++) 
{
    for (l = 0; l < captionarray.length; l++) 
    {

        if(getkeywords[k] == captionarray[l])
        {


            found=1;
            break;

        }
    }

    if(found==1)
    {
        alert('Found > ' + getkeywords[k] + ':filter image');
        found=0;  


    }
    else
    {
        alert('not found > ' + getkeywords[k] + ':filter image');

    }
}

希望有所帮助..

答案 2 :(得分:0)

在警告结果之前,您必须将值与第二个数组中的所有项进行比较 我更新了你的jsfiddle - 试试http://jsfiddle.net/ZvmHx/5/

var getkeywords = ["John","Frank","Sarah"]; 
var captionarray = ["Jim","Joe","Lee","Steve","John","Michelle","Brad"];    

imagecode = '';
for (k = 0; k < getkeywords.length; k++) {
    var isExists = false;
    for (l = 0; l < captionarray.length; l++) {
        if (getkeywords[k] == captionarray[l]){                     
            isExists = true;
            break;
        }
    }

    if (isExists) {
        alert('Found > ' + getkeywords[k] + ':filter image');
    } else {
        alert('not found > ' + getkeywords[k] + ':filter image');
    }
}