0

我正在尝试将两个数组的值相互比较。如果找到匹配项 - 执行某项操作 - 否则执行此操作。

我在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');

    }
  }
}
4

3 回答 3

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');

    }
}
于 2013-07-06T12:31:34.310 回答
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');

    }
}

希望有帮助..

于 2013-07-06T12:33:10.533 回答
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');
    }
}
于 2013-07-06T12:34:26.997 回答