[英]set a year range in javascript
How can I define an array range without specifying each option in javascript? 如何在不指定javascript中每个选项的情况下定义数组范围?
Right now I have this: 现在我有这个:
var year = {
'0': '2000',
'1': '2001',
'2': '2002',
'3': '2003',
'4': '2004',
'5': '2005',
'6': '2006',
'7': '2007',
'8': '2008',
'9': '2009'
};
You said you want an array, but you have a plain old object in your example. 您说过要一个数组,但是示例中有一个普通的旧对象。 From your comment on this answer, however, it sounds like you really do want a normal object, so that's what I'll use.
但是,从您对这个答案的评论看来,您确实确实想要一个普通的对象,所以这就是我要使用的对象。
At any rate, you can do this with a loop: 无论如何,您可以通过循环执行此操作:
var year = {}; //or use [] if you want an array
var min_year = 2000;
var max_year = 2009;
for(var i = 0; i <= max_year - min_year; i++) {
year[i] = i + min_year;
}
alert(year[5]); //2005
You can expand on this example to suit your needs. 您可以根据需要扩展此示例。
You don't have to use a loop to solve the issue 您不必使用循环来解决问题
var startYr = 2000;
var year = function(i){
return i + startYr;
};
// usage
year(0);
// output
2000
Your code example and your question are completely different: 您的代码示例和问题完全不同:
This is considered to be an object 这被认为是一个对象
var variable = {};
Whereas this is considered to be an array 而这被认为是一个数组
var variable = [];
There is a slight difference between them. 它们之间有细微差别。 For more information on the topic you can check What is the difference between an array and an object?
有关该主题的更多信息,您可以检查数组和对象之间的区别是什么?
So, if you actually need an javascript array this code should do the work: 因此,如果您实际上需要一个javascript数组,则此代码可以完成工作:
function generate_year_range(start, end){
var years = [];
for(var year = start; year <= end; year++){
years.push(year)
}
return years;
}
var my_years = generate_year_range(2000,2009);
This will generate the years from 2000 to 2009(including) and store them into an array. 这将产生从2000年到2009年(包括)的年份,并将它们存储到一个数组中。 So, your
my_years
variable will hold [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
. 因此,您的
my_years
变量将保持[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.