我试图使用几个for循环来遍历一个字符串数组来调用每个数组项。我在找到合适的代码来解决它时遇到了一些麻烦。我尝试过使用数组的全局定义等等。
var An = new Array(
"11111100011111",
"11111000011111",
"11110011001111",
"11100000000111",
"11001111110011",
"10011111111001");
var Bn = new Array(
"1000000001",
"1001111001",
"1000000001",
"1000000001",
"1001111001",
"1000000001");
// This second part sits in a onload function.
var alphabet = "AB".split("");
for (x = 0; x < 6; x++) {
for (i = 0; i < 2; i++) {
var my_object = {};
my_object = window[alphabet[x] + 'n[' + i + ']'];
my_object = window[my_object].replace(/0/g, "B");
my_object = window[my_object].replace(/1/g, "_");
}
}
答案 0 :(得分:2)
您应该做的是将An
和Bn
放入对象中。这将使以后更容易引用 。
var alphabet = {
An: [
"11111100011111",
"11111000011111",
"11110011001111",
"11100000000111",
"11001111110011",
"10011111111001"
],
Bn: [
"1000000001",
"1001111001",
"1000000001",
"1000000001",
"1001111001",
"1000000001"
]
};
然后你选择你想要的数组并循环它。
var arrays = ['A', 'B'];
for(var x = 0, xLen = arrays.length; x < xLen; x++){
var my_key = arrays[x]+'n';
for(var i = 0, iLen = alphabet[my_key].length; i < iLen; i++){
alphabet[my_key][i] = alphabet[my_key][i].replace(/0/g, "B");
alphabet[my_key][i] = alphabet[my_key][i].replace(/1/g, "_");
}
}
实际上,对于内部for
循环,您还可以使用Array.map
。
var arrays = ['A', 'B'];
for(var x = 0, xLen = arrays.length; x < xLen; x++){
var my_key = arrays[x]+'n';
alphabet[my_key] = alphabet[my_key].map(function(val){
val = val.replace(/0/g, "B");
val = val.replace(/1/g, "_");
return val;
});
}