所以我有这个数组:
var utf = Array(
a: Array('á','à','ã','Á','À','Ã'),
e: Array('é','ê','É','È'),
i: Array('í','Í'),
o: Array('ó','õ','Ó','Õ'),
u: Array('ú','Ú'),
c: Array('ç','Ç')
);
我想运行一个for循环,如:
for(i = 0; i < utf.length; i++){
for (j = 0; j < utf[i].length; j++){
mystring.replace(utf[i][j], <utf[i][arrayname]>);
}
}
这可能吗?怎么样?你会以不同的方式做到这一点吗?如何?
非常感谢
答案 0 :(得分:5)
function doReplace(mystring)
{
var utf = {
a: ['á','à','ã','Á','À','Ã'],
e: ['é','ê','É','È'],
i: ['í','Í'],
o: ['ó','õ','Ó','Õ'],
u: ['ú','Ú'],
c: ['ç','Ç']
};
for(var c in utf)
{
var charArray = utf[c];
for (var j = 0; j < charArray.length; j++)
{
mystring= mystring.replace(new RegExp(charArray[j], "g"), c);
}
}
return mystring;
}
这很慢。如果您的浏览器编译正则表达式(如大多数新版本),最快的解决方案可能是每个字符使用一个正则表达式:
var utf = {
a: ['á','à','ã','Á','À','Ã'],
e: ['é','ê','É','È'],
i: ['í','Í'],
o: ['ó','õ','Ó','Õ'],
u: ['ú','Ú'],
c: ['ç','Ç']
};
var utfRegexes = {};
// Sadly javascript isn't C# so something that could be done in two lines
// of LINQ need to be unrolled.
for(var c in utf)
{
console.log("in " + c);
var chars = "[";
for (var j = 0; j < utf[c].length; j++)
{
chars += utf[c][j];
}
chars += "]";
utfRegexes[c] = new RegExp(chars, "g");
}
function doReplaceRegex(mystring)
{
for(var c in utfRegexes)
{
mystring = mystring.replace(utfRegexes[c], c);
}
return mystring;
}
答案 1 :(得分:2)
Javascript中的数组仅支持整数索引。使用对象。我还建议使用JSON作为创建新数组和对象的最可读和最简单的方法:
var utf = {
a: ['á','à','ã','Á','À','Ã'],
e: ['é','ê','É','È']
//etc
};
for (var i in utf)
{
//In the i variable, you'll find name of array of chars: a, e, i, o, u, c...
//The array of chars can be found in utf[i]
}
答案 2 :(得分:0)
可以使用关联数组(即对象)而不是普通数组。
var utf = {
'a': ['á','à','ã','Á','À','Ã'],
'e': ['é','ê','É','È'],
'i': ['í','Í'],
'o': ['ó','õ','Ó','Õ'],
'u': ['ú','Ú'],
'c': ['ç','Ç']
}
var mystring = 'abgvÁÓÚ';
for(var i in utf){
for(var j = 0; j < utf[i].length; j++){
mystring.replace(utf[i][j], i);
}
}
答案 3 :(得分:0)
// Just a semantic reformat, lacks speed improvements
var utf = Array(
Array('a', 'á','à','ã','Á','À','Ã'),
Array('e', 'é','ê','É','È'),
Array('i', 'í','Í'),
Array('o', 'ó','õ','Ó','Õ'),
Array('u', 'ú','Ú'),
Array('c', 'ç','Ç')
);
for(i = 0; i < utf.length; i++){
for j = 1; j < utf[i].length; j++){
mystring.replace(utf[i][j], utf[i][0]);
}
}