2

提前感谢任何能想到更有效或更好的方法来执行我下面的 Javascript 代码的人:

var availableCharacters=Array("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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");

for (counter=0; counter<availableCharacters.length; counter++){
  if(availableCharacters[counter]=="i"||
     availableCharacters[counter]=="l"||
     availableCharacters[counter]=="I"||
     availableCharacters[counter]=="L"||
     availableCharacters[counter]=="1"||
     availableCharacters[counter]=="0"||
     availableCharacters[counter]=="O"){
      availableCharacters.splice(counter, 1);
    }
}

我要做的是遍历一个数组并删除该数组中“i”、“l”、“I”、“L”、“1”、“0”或“O”的任何元素。虽然这确实有效,但它似乎可能很慢而且有点麻烦。如果有更好的方法?如果不是,那不是问题,但大多数时候当我做一些对我来说不合适的事情时,它不是!所以我想我会问

谢谢 :)

4

5 回答 5

6

更新的浏览器支持Array.filter

var availableCharacters = ........;
availableCharacters = availableCharacters.filter(function(a) {
  return !a.match(/[ilLI10O]/);
});

然而,对于较旧的浏览器,Mark Linus 给出的 for 循环很好。

于 2012-06-19T21:24:33.060 回答
4
var availableCharacters=["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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (counter=0; counter<availableCharacters.length; counter++){
    if(/[ilIL10O]/.test(availableCharacters[counter])){
        availableCharacters.splice(counter, 1);
    }
}
于 2012-06-19T21:21:41.153 回答
1

具有简单过滤器列表的替代解决方案:

var availableCharacters=Array("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", "0", "1", "2", "3",     "4", "5", "6", "7", "8", "9");
var filter = ['i', 'l', 'I', 'L', '1', '0', 'O'];
for (counter=0; counter<availableCharacters.length; counter++){
    if(filter.indexOf(availableCharacters[counter]) >= 0) {
        availableCharacters.splice(counter, 1);
    }
}
于 2012-06-19T21:23:03.337 回答
0

如果你愿意使用jQuery,你可以grep()像这样使用和编写它:

在这里提琴

var availableChars = ["a", "b", "c", '1', 'i', 'o', "9"];
var result = $.grep(availableChars, function(c) {
    return !c.match(/[^il10o]/i)
})
document.write(result)​
于 2012-06-19T21:29:19.393 回答
0

过滤器很好,但是一个简单的字符串替换可以在没有网络的情况下工作

   var availableCharacters=["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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

  var allowed= availableCharacters.join('').replace(/[iLl10O]/g,'').split('');

  returned value: (Array)
  a,b,c,d,e,f,g,h,j,k,m,n,o,p,q,r,s,t,u,v,w,x,y,z,2,3,4,5,6,7,8,9
于 2012-06-20T01:48:49.997 回答