JavaScript 中选择框的年份范围

2022-01-24 00:00:00 arrays range javascript

我正在尝试在 JavaScript 中创建一个动态选择框,其中包含从某个"年份开始到当前年份结束的年份.JavaScript中有没有像Ruby的 range 类的东西,还是我必须循环多年来使用 for 循环?

I'm trying to create a dynamic select box in JavaScript with a range of years starting with 'some' year and ending with the current year. Is there anything like Ruby's range class in JavaScript or do I have to loop trough the years using a for loop?

这就是我想出的,尽管我认为在 Ruby 中考虑的有点多,我可以只使用一个范围.

Here's what I've come up with though I think it's a bit much considering in Ruby I can just use a range.

    this.years = function(startYear){
        startYear = (typeof(startYear) == 'undefined') ? 1980 : startYear
        var currentYear = new Date().getFullYear();
        var years = []
        for(var i=startYear;i<=currentYear;i++){
            years.push(i);
        } 
        return years;
    }

推荐答案

JavaScript 确实有 Range 对象,但它指的是 DOM 的任意部分,IE 6/7 不支持.

JavaScript does have a Range object, but it refers to an arbitrary portion of the DOM and is not supported in IE 6/7.

如果你愿意,你可以把你的函数简化成这样,但其实都是一样的.

If you want, you can simplify your function to this, but it's all the same really.

this.years = function(startYear) {
    var currentYear = new Date().getFullYear(), years = [];
    startYear = startYear || 1980;  
    while ( startYear <= currentYear ) {
        years.push(startYear++);
    }   
    return years;
}
 
console.log( this.years(2019-20));

相关文章