O JavaScript tem um método como "range()" para gerar um range dentro dos limites fornecidos?

Em PHP, você pode fazer...

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

Ou seja, há uma função que permite obter uma gama de números ou caracteres, passando os limites superior e inferior.

Há algo incorporado ao JavaScript nativamente para isto? Se não, como eu o implementaria?

Solução

Funciona para personagens e números, avançando ou recuando com um passo opcional.


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 
Comentários (0)

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

O Javascript padrão não tem't tem uma função integrada para gerar intervalos. Vários frameworks javascript adicionam suporte a tais características, ou como outros apontaram, você pode sempre rolar o seu próprio.

Se você'gostaria de verificar novamente, o recurso definitivo é o ECMA-262 Standard.

Comentários (4)