简体   繁体   English

Javascript:从数组设置变量

[英]Javascript: setting a var from an array

I have an array of months like this: 我有几个月这样的数组:

var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];

What i am trying to do is make the name of the month a variable and set an object to it like so: 我想做的是使月份的名称为变量,并为其设置一个对象,如下所示:

for(i=0;i<11;i++){
months[i] = $(".bitem:eq("+i+")");
}

But that just replaces months[i] ( if i=0 for example it would replace "jan" with the object). 但这只是替换了months[i] (例如, if i=0 ,它将用对象替换“ jan”)。 What i want to do is use the string that months[i] is equal to for the variable name. 我想做的是使用months[i]等于变量名的字符串。 I tried using .toString() like this: 我试过像这样使用.toString()

for(i=0;i<11;i++){
months[i].toString() = $(".bitem:eq("+i+")");
}

but I get the error: 但是我得到了错误:

Error: ReferenceError: invalid assignment left-hand side

Why exactly do you need to have variables names jan , feb , etc? 为什么需要精确地使用变量名称janfeb等? From what I can tell, you can do everything you want by using a plain old object with properties: 据我所知,您可以通过使用带有属性的普通旧对象来完成所需的一切:

var monthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];

var months = {};
for(var i = 0; i < monthNames.length; i++) {
    months[monthNames[i]] = $(".bitem:eq("+i+")");
}

// Example usage
var januaryItem = months["jan"];
// or equivalent: months.jan;

Instead of creating variables, make an object that can translate the string to the index in the array: 代替创建变量,创建一个可以将字符串转换为数组中索引的对象:

var monthIndex = {
  "jan": 0, "feb": 1, "mar": 2, "apr": 3, "may": 4, "jun": 5,
  "jul": 6, "aug": 7, "sep": 8, "oct": 9, "nov": 10, "dec": 11
};
var months = $(".bitem");

Now given any of the month names, you can get the corresponding element from the array: 现在给定任何月份名称,您就可以从数组中获取相应的元素:

var m = 'aug';
var element = months[monthIndex[m]];

You can also use specific month names to get the index: 您还可以使用特定的月份名称来获取索引:

var element = months[monthIndex.aug];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM