JavaScript function similar to Python range()

前端 未结 24 1612
南旧
南旧 2020-11-30 21:17

Is there a function in JavaScript similar to Python\'s range()?

I think there should be a better way than to write the following lines every time:

24条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 21:45

    Here you go.

    This will write (or overwrite) the value of each index with the index number.

    Array.prototype.writeIndices = function( n ) {
        for( var i = 0; i < (n || this.length); ++i ) this[i] = i;
        return this;
    };
    

    If you don't provide a number, it will use the current length of the Array.

    Use it like this:

    var array = [].writeIndices(10);  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

提交回复
热议问题