有人可以帮我找到一个更好的替代这个Javascript for循环我写的吗?

时间:2012-06-19 21:20:11

标签: javascript loops for-loop

提前感谢任何能够考虑使用以下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”的所有元素”。虽然这确实有效,但似乎它可能很慢而且有点麻烦。如果有更好的方法?如果不是那么不是问题,但大多数时候,当我做一些对我来说不合适的事情时,事实并非如此!所以我想我会问S.O。

谢谢:)

5 个答案:

答案 0 :(得分:6)

更新的浏览器支持Array.filter

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

但是对于旧版浏览器,Mark Linus给出的for循环很好。

答案 1 :(得分: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);
    }
}

答案 2 :(得分: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);
    }
}

答案 3 :(得分:0)

如果您愿意使用jQuery you can use grep()并将其写为:

Fiddle here

var availableChars = ["a", "b", "c", '1', 'i', 'o', "9"];
var result = $.grep(availableChars, function(c) {
    return !c.match(/[^il10o]/i)
})
document.write(result)​

答案 4 :(得分: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