function illegal_chr(input) {
//checks 'entry_box' for illegal characters
document.getElementById("binary_p").innerHTML = "Convert binary to text or text to binary."
var entry_value = document.getElementById("entry_box").value;
var entry_length = entry_value.length
var CHARACTERS_ARRAY = []
var illegal_message_bin = "Please ensure you have only used binary."
var ILLEGAL_BIN = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "[", "]", "#", "'", ";", ",", ".", "`", "¬", "?", ">", "<", "~", "@", ":", "}", "{", "|", "/", "!", "£", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "2", "3", "4", "5", "6", "7", "8", "9"]
//adds each character to 'CHARACTERS_ARRAY'
for (var c = 0; c < entry_length; c += 1) {
character = entry_value[c];
CHARACTERS_ARRAY.push(character)
}
//loops through 'CHARACTERS_ARRAY' checking for any illegal characters
for (var ch = 0; ch < CHARACTERS_ARRAY.length; ch += 1) {
characters = CHARACTERS_ARRAY[ch];
for (var ill = 0; ill < ILLEGAL_BIN.length; ill += 1) {
letters = ILLEGAL_BIN[ill]
if (characters == letters) {
document.getElementById("binary_p").innerHTML = illegal_message_bin;
}
else if (characters != letters && ch == entry_length) {
alert("test")
}
}
}
}
该功能会检查用户是否使用过任何“非法字符”,这是否有效但是当它不包含“非法”字符时,没有任何事情发生?
答案 0 :(得分:2)
只是单挑,你可以使用正则表达式,因为@duffymo声明:
function isHex(str) {
return str.match(/^[a-f0-9]{6}$/i) !== null;
}
检查二进制数(至少一个0或1):
function isBin(str) {
return str.match(/^[0,1].*$/) !== null;
}
答案 1 :(得分:1)
答案 2 :(得分:0)
if(conditionA){
//do something
}
else if(conditionB){
//do something else
}
这大致相当于
if(conditionA){
//do something
}
**if(!conditionA && conditionB)**{
//do something else
}
在你的“else if conditional”中,它自动表示满足条件“characters!= letters”。
else if (characters != letters && ch == entry_length)
因此可以写成
else if (ch == entry_length)
在for循环的每次迭代中,ch指的是CHARACTERS_ARRAY的每个元素。假设
您在entry_box输入元素中输入了文本 abc
这意味着变量entry_value包含字符串“abc”
并且entry_length包含3 [您输入的文本的长度]
并继续进行代码,CHARACTERS_ARRAY包含数组['a','b','c']
和CHARACTERS_ARRAY.length也是3
for循环开始 - for循环迭代1:ch包含0 - for循环迭代2:ch包含1 - for循环迭代3:ch包含2 for loop ends
entry_length是3,因此永远不等于改变ch&amp;你永远不会看到警报。
正如duffymo建议的那样,使用正则表达式会非常简单!