JavaScript ha un metodo come "range()" per generare un intervallo entro i limiti forniti?

In PHP, puoi fare...

range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")

Cioè, c'è una funzione che ti permette di ottenere un intervallo di numeri o caratteri passando i limiti superiore e inferiore.

C'è qualcosa incorporato in JavaScript nativamente per questo? Se no, come potrei implementarlo?

Soluzione

Funziona per caratteri e numeri, andando avanti o indietro con un passo opzionale.


var range = function(start, end, step) {
    var range = [];
    var typeofStart = typeof start;
    var typeofEnd = typeof end;

    if (step === 0) {
        throw TypeError("Step cannot be zero.");
    }

    if (typeofStart == "undefined" || typeofEnd == "undefined") {
        throw TypeError("Must pass start and end arguments.");
    } else if (typeofStart != typeofEnd) {
        throw TypeError("Start and end arguments must be of same type.");
    }

    typeof step == "undefined" && (step = 1);

    if (end < start) {
        step = -step;
    }

    if (typeofStart == "number") {

        while (step > 0 ? end >= start : end  0 ? end >= start : end 
Commentari (0)

Array.range= function(a, b, step){
    var A= [];
    if(typeof a== 'number'){
        A[0]= a;
        step= step || 1;
        while(a+step
Commentari (1)

Il Javascript standard non ha una funzione integrata per generare intervalli. Diversi frameworks javascript aggiungono il supporto per tali funzioni, o come altri hanno sottolineato si può sempre rollare il proprio.

Se volete ricontrollare, la risorsa definitiva è lo standard ECMA-262.

Commentari (4)