Javascript循环字符测试中的循环

Bar*_*der 2 javascript jquery loops

我有一个循环,通过一个巨大的字符串.检查每个数字与另一个字符串中的个别数字,并突出显示匹配...

var decypher = "782137829431783498892347847823784728934782389";

var systemPass = "789544";

for (var x = 0; x < decypher.length; x++) { //loop through the array
    var switcher = 0; //not run this row yet
    for (var p = 0; p < systemPass.length; p++) { //loop through each digit in the password
        if(eval(decypher[x]) === eval(systemPass[p])) { //if the password digit matches the array digit
            if (switcher === 0) { //not run yet...
                $('body').append("<p style='color: green; float: left;'>"+decypher[x]+"</p>");
                switcher = 1; //finished running
            }
        } else { //no match
            if (switcher === 0) { //not run yet...
                $('body').append("<p style='color: silver; float: left;'>"+decypher[x]+"</p>");
                switcher = 1; //finished running
            }
        } 
    }   
}
Run Code Online (Sandbox Code Playgroud)

JSFiddle示例:http://jsfiddle.net/neuroflux/J4wbk/12/

我的问题是,为什么它只是突出了7's?多年来我一直在摸不着头脑!

[编辑]
感谢"@Yograj Gupta" - 我删除了switcher变量,但现在我得到了每个角色的多个实例:http://jsfiddle.net/neuroflux/J4wbk/22/

Sco*_*yet 6

好吧,你肯定是这么做的.indexOf改为使用(或者,正如约翰所指出的那样jQuery.inArray):

http://jsfiddle.net/CrossEye/euGLn/1/

var decypher = "782137829431783498892347847823784728934782389";
var systemPass = "789544";

for (var x = 0; x < decypher.length; x++) {
    // if(systemPass.indexOf(decypher[x]) > -1) { // Thanks, Johan
    if ($.inArray(decypher[x], systemPass) > -1) {
        $('body').append("<p style='color: green; float: left;'>"+decypher[x]+"</p>");
    } else { //no match
        $('body').append("<p style='color: silver; float: left;'>"+decypher[x]+"</p>");
    } 
}
Run Code Online (Sandbox Code Playgroud)

虽然这里有很多其他清理建议,但至少循环更容易.

- 斯科特