如何在数组名

时间:2015-11-27 13:26:12

标签: javascript arrays variables while-loop

我有5个数组,每个数组内有8个字符串。每个数组的名称都被数字所取代,例如'titles1','titles2'......我想创建一个while循环来检查每个数组中的每个字符串。我目前遇到的问题是我无法更改数组名称中的数字(从1到5 - titles1,2,3 ......)。知道我怎么能让它工作吗?但是代码可以工作,因为数组名称现在是一个字符串,它不会检查数组中的任何内容。

var i = 0; var j = 1; var titles = '';
while(j <= 5) {
    titles = 'titles' + j;
    while(titles1.length >= i) {
        if (searchBookInput === titles[i]) {
            return titles[i] + ' is available';
        }
        i++;
    } j++; i = 0;
}

4 个答案:

答案 0 :(得分:5)

您可以将五个数组放入一个对象并迭代其键,而不是尝试迭代变量名称:

var myObj = {
    titles1: ["The", "quick", "fox", "jumps", "over", "the", "lazy", "dog"],
    titles2: ["The", "quick", "fox", "jumps", "over", "the", "lazy", "dog"],
    titles3: ["The", "quick", "fox", "jumps", "over", "the", "lazy", "dog"],
    titles4: ["The", "quick", "fox", "jumps", "over", "the", "lazy", "dog"],
    titles5: ["The", "quick", "fox", "jumps", "over", "the", "lazy", "dog"]
};

for (var key in myObj) {
    var array = myObj[key]; //array will be titles1, titles2, ...
    //do your stuff here...        
}

这很有效,因为在JavaScript中,您可以通过两种方式访问​​对象的值:

object.someValue

object["someValue"]

答案 1 :(得分:1)

最好使用多维数组,而不是为名称添加数字(这是不可能的顺便说一句):

var i = 0;
var j = 1;
var titles = new Array();

while (j <= 5){ // building your two-dimensional array
    var array = new Array();
    titles[j] = array;
    j++;
}

while(j <= 5) {
    while(titles[j].length <= i) {
        if (searchBookInput === titles[j][i]) {
            return titles[j][i] + ' is available';
        }
        i++;
    }
j++;
i = 0;
}

多维数组解释:http://www.javascripter.net/faq/twodimensional.htm

编辑:我可能犯了语法错误,javascript已经有一段时间了。

答案 2 :(得分:0)

您可以创建一个多维对象,每个对象都包含一组具有相应标题的书籍,如下所示:

searchBookInput = "The Martian"

books = [{"title" : "The Martian"}, {"title" : "War And Peace"}, {"title" : "The Art of War"}]
comics = [{"title" : "Ms Marvel"}, {"title" : "Saga"}, {"title": "The Walking Dead"}]

books.filter(function(book) {return book.title == searchBookInput})
// Returns the object with the title matching searchBookInput
comics.filter(function(toon) {return toon.title == searchBookInput})
// Returns no object as no comic matches searchBookInput

这比需要多维数组的迭代更容易。

答案 3 :(得分:-2)

我认为 eval 可能是您的朋友。 eval解决方案并不完全理想,因为它会污染全局命名空间(我认为)。所以,另一个解决方案可能是:

var i = 0; var j = 1; var titles = '';
while(j <= 5) {
    titles = eval('titles' + j);
    while(titles.length >= i) {
        if (searchBookInput === titles[i]) {
            return titles[i] + ' is available';
        }
        i++;
    } j++; i = 0;
}