在PHP中,您可以。。。

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

也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。

JavaScript本机是否有内置的功能?如果没有,我将如何实施?


当前回答

它适用于字符和数字,通过可选步骤向前或向后移动。

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 <= start) {
            range.push(start);
            start += step;
        }

    } else if (typeofStart == "string") {

        if (start.length != 1 || end.length != 1) {
            throw TypeError("Only strings with one character are supported.");
        }

        start = start.charCodeAt(0);
        end = end.charCodeAt(0);

        while (step > 0 ? end >= start : end <= start) {
            range.push(String.fromCharCode(start));
            start += step;
        }

    } else {
        throw TypeError("Only string and number types are supported");
    }

    return range;

}

jsFiddle。

如果扩充本机类型是您的事情,那么将其分配给Array.range。

var范围=函数(开始、结束、步骤){var范围=[];var typeofStart=启动类型;var typeofEnd=结束类型;如果(步骤==0){throw TypeError(“步长不能为零。”);}if(类型开始==“undefined”| |类型结束==“未定义”){throw TypeError(“必须传递开始和结束参数。”);}否则如果(typeofStart!=typeofEnd){throw TypeError(“开始和结束参数必须是相同的类型。”);}步骤类型==“未定义”&&(步骤=1);if(结束<开始){step=-步骤;}if(开始类型==“number”){while(步骤>0?结束>=开始:结束<=开始){范围.推(启动);开始+=步骤;}}否则if(typeofStart==“string”){如果(start.length!=1 | | end.length;=1){throw TypeError(“仅支持带有一个字符的字符串。”);}start=start.charCodeAt(0);end=end.charCodeAt(0);while(步骤>0?结束>=开始:结束<=开始){range.push(String.fromCharCode(开始));开始+=步骤;}}其他{throw TypeError(“仅支持字符串和数字类型”);}返回范围;}console.log(范围(“A”,“Z”,1));console.log(范围(“Z”,“A”,1));console.log(范围(“A”,“Z”,3));console.log(范围(0,25,1));console.log(范围(0,25,5));console.log(范围(20,5,5));

其他回答

只是在Elquent JavaScript中做了这样的练习

function range(start, end, step) {
  var ar = [];
  if (start < end) {
    if (arguments.length == 2) step = 1;
    for (var i = start; i <= end; i += step) {
      ar.push(i);
    }
  }
  else {
    if (arguments.length == 2) step = -1;
    for (var i = start; i >= end; i += step) {
      ar.push(i);
    }
  }
  return ar;
}

我会这样编码:

function range(start, end) {
    return Array(end-start).join(0).split(0).map(function(val, id) {return id+start});
}  

range(-4,2);
// [-4,-3,-2,-1,0,1]

range(3,9);
// [3,4,5,6,7,8]

它的行为类似于Python范围:

>>> range(-4,2)
[-4, -3, -2, -1, 0, 1]

如果我们输入类似[4,2]的内容,我们将得到[2,3,4]作为输出,我们可以使用它。

function createRange(array) {
  var range = [];
  var highest = array.reduce(function(a, b) {
    return Math.max(a, b);
  });
  var lowest = array.reduce(function(a, b) {
    return Math.min(a, b);
  });
  for (var i = lowest; i <= highest; i++) {
    range.push(i);
  }
  return range;
}

可以如下创建大量使用ES6的相当简约的实现,特别注意Array.from()静态方法:

const getRange = (start, stop) => Array.from(
  new Array((stop - start) + 1),
  (_, i) => i + start
);

我发现了一个与PHP中的函数相当的JS范围函数,在这里工作得非常棒。向前和向后工作,可以处理整数、浮点数和字母!

function range(low, high, step) {
  //  discuss at: http://phpjs.org/functions/range/
  // original by: Waldo Malqui Silva
  //   example 1: range ( 0, 12 );
  //   returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  //   example 2: range( 0, 100, 10 );
  //   returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
  //   example 3: range( 'a', 'i' );
  //   returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
  //   example 4: range( 'c', 'a' );
  //   returns 4: ['c', 'b', 'a']

  var matrix = [];
  var inival, endval, plus;
  var walker = step || 1;
  var chars = false;

  if (!isNaN(low) && !isNaN(high)) {
    inival = low;
    endval = high;
  } else if (isNaN(low) && isNaN(high)) {
    chars = true;
    inival = low.charCodeAt(0);
    endval = high.charCodeAt(0);
  } else {
    inival = (isNaN(low) ? 0 : low);
    endval = (isNaN(high) ? 0 : high);
  }

  plus = ((inival > endval) ? false : true);
  if (plus) {
    while (inival <= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival += walker;
    }
  } else {
    while (inival >= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival -= walker;
    }
  }

  return matrix;
}

这是缩小版:

function range(h,c,b){var i=[];var d,f,e;var a=b||1;var g=false;if(!isNaN(h)&&!isNaN(c)){d=h;f=c}else{if(isNaN(h)&&isNaN(c)){g=true;d=h.charCodeAt(0);f=c.charCodeAt(0)}else{d=(isNaN(h)?0:h);f=(isNaN(c)?0:c)}}e=((d>f)?false:true);if(e){while(d<=f){i.push(((g)?String.fromCharCode(d):d));d+=a}}else{while(d>=f){i.push(((g)?String.fromCharCode(d):d));d-=a}}return i};