我可以在javascript中将变量设置为变量组合吗?

时间:2014-04-06 22:31:14

标签: javascript

这是我的代码:

var album1 = "First Album name";
var album2 = "Second Album Name";
var album3 = "Third Album Name";
var album4 = "Fourth Album name";
var album5 = "Fifth Album name";

var currentAlbumCtr = 1;
var currentAlbum = album + currentAlbumCtr;

如果currentAlbumCtr为1,currentAlbum应该设置为album1。任何人都可以帮忙吗?

4 个答案:

答案 0 :(得分:3)

您可以使用eval来达到您想要的效果,但这可能是错误的做法。为什么不使用数组:

var album = [];
album[1] = "First Album name";
album[2] = "Second Album Name";
album[3] = "Third Album Name";
album[4] = "Fourth Album name";
album[5] = "Fifth Album name";

currentAlbumCtr = 1;
currentAlbum = album[currentAlbumCtr];

或者,或者,

var album = {
    "1": "First Album name";
    "2": "Second Album Name";
    "3": "Third Album Name";
    "4": "Fourth Album name";
    "5": "Fifth Album name";
};

甚至

var album = [
    "First Album name",
    "Second Album Name",
    "Third Album Name",
    "Fourth Album name",
    "Fifth Album name"
];

currentAlbumCtr = 1;
currentAlbum = album[currentAlbumCtr-1];

注意最后一个语句的-1,因为数组通常从0开始索引

答案 1 :(得分:0)

  如果currentAlbumCtr为1,

currentAlbum应设置为album1。

if (currentAlbumCtr == 1) {
    currentAlbum = album1;
}

答案 2 :(得分:0)

不完全确定你要求的是什么。 this有效吗?

<强>脚本:

var albums =
           [ "album1",
             "album2",
             "album3" ];

$("#clickme").click(function(){
    var currentAlbum = parseInt($("#album_number").val()) % albums.length;
    alert(albums[currentAlbum]);
})

<强> HTML:

<button id="clickme">click!</button>
<input id="album_number"></input>

答案 3 :(得分:-1)

var currentAlbum = eval("album" + currentAlbumCtr);