我有一个循环遍历一大串字符。检查每个数字与另一个字符串中的各个数字并突出显示匹配项...
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
}
}
}
}
JSFiddle 示例:http://jsfiddle.net/neuroflux/J4wbk/12/
我的问题是,为什么它只突出显示 7
?多年来我一直在为这个问题摸不着头脑!
[编辑]
感谢“@Yograj Gupta” - 我删除了 switcher
变量,但现在我得到了每个 Angular 色的多个实例:http://jsfiddle.net/neuroflux/J4wbk/22/
最佳答案
嗯,你肯定是在以困难的方式做这件事。使用 indexOf
代替(或者,正如 Johan 指出的,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>");
}
}
虽然这里还有很多其他的清理工作值得推荐,但至少循环更容易。
--斯科特
关于Javascript 在循环中循环字符测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12600621/