在PHP中,您可以。。。

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

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

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


当前回答

Array.range = function(a, b, step){
    var A = [];
    if(typeof a == 'number'){
        A[0] = a;
        step = step || 1;
        while(a+step <= b){
            A[A.length]= a+= step;
        }
    }
    else {
        var s = 'abcdefghijklmnopqrstuvwxyz';
        if(a === a.toUpperCase()){
            b = b.toUpperCase();
            s = s.toUpperCase();
        }
        s = s.substring(s.indexOf(a), s.indexOf(b)+ 1);
        A = s.split('');        
    }
    return A;
}
    
    
Array.range(0,10);
// [0,1,2,3,4,5,6,7,8,9,10]
    
Array.range(-100,100,20);
// [-100,-80,-60,-40,-20,0,20,40,60,80,100]
    
Array.range('A','F');
// ['A','B','C','D','E','F')
    
Array.range('m','r');
// ['m','n','o','p','q','r']

其他回答

这可能不是最好的方法。但是如果你想在一行代码中得到一系列数字。例如10-50

Array(40).fill(undefined).map((n, i) => i + 10)

其中40是(结束-开始),10是开始。这应该返回[10,11,…,50]

使用TypeScript设置(应用程序范围):

declare global {
  interface Function {
    range(count: number, start_with: number): number[];
  }
}

Function.prototype.range = function (
  count: number,
  start_with: number = 0
): number[] {
  return [...Array(count).keys()].map((key) => key + start_with);
};

使用JS设置:

Function.prototype.range = function(count, start_with=0){
    return [...Array(count).keys()].map((key) => key + start_with);
}

使用示例:

Function.range(2,0) //Will return [0,1]
Function.range(2,1) //Will return [1,2]
Function.range(2,-1) //Will return [-1,0]

要紧密复制的类型脚本函数

/**
 * Create a generator from 0 to stop, useful for iteration. Similar to range in Python.
 * See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
 * See: https://docs.python.org/3/library/stdtypes.html#ranges
 * @param {number | BigNumber} stop
 * @returns {Iterable<number>}
 */
export function range(stop: number | BigNumber): Iterable<number>
/**
 * Create a generator from start to stop, useful for iteration. Similar to range in Python.
 * See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
 * See: https://docs.python.org/3/library/stdtypes.html#ranges
 * @param {number | BigNumber} start
 * @param {number | BigNumber} stop
 * @returns {Iterable<number>}
 */
export function range(
  start: number | BigNumber,
  stop: number | BigNumber,
): Iterable<number>

/**
 * Create a generator from start to stop while skipping every step, useful for iteration. Similar to range in Python.
 * See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
 * See: https://docs.python.org/3/library/stdtypes.html#ranges
 * @param {number | BigNumber} start
 * @param {number | BigNumber} stop
 * @param {number | BigNumber} step
 * @returns {Iterable<number>}
 */
export function range(
  start: number | BigNumber,
  stop: number | BigNumber,
  step: number | BigNumber,
): Iterable<number>
export function* range(a: unknown, b?: unknown, c?: unknown): Iterable<number> {
  const getNumber = (val: unknown): number =>
    typeof val === 'number' ? val : (val as BigNumber).toNumber()
  const getStart = () => (b === undefined ? 0 : getNumber(a))
  const getStop = () => (b === undefined ? getNumber(a) : getNumber(b))
  const getStep = () => (c === undefined ? 1 : getNumber(c))

  for (let i = getStart(); i < getStop(); i += getStep()) {
    yield i
  }
}

ES6

使用Array.from(此处为文档):

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
/**
 * @param {!number|[!number,!number]} sizeOrRange Can be the `size` of the range (1st signature) or a
 *   `[from, to]`-shape array (2nd signature) that represents a pair of the *starting point (inclusive)* and the
 *   *ending point (exclusive)* of the range (*mathematically, a left-closed/right-open interval: `[from, to)`*).
 * @param {!number} [fromOrStep] 1st signature: `[from=0]`. 2nd signature: `[step=1]`
 * @param {!number} [stepOrNothing] 1st signature: `[step=1]`. 2nd signature: NOT-BEING-USED
 * @example
 * range(5) ==> [0, 1, 2, 3, 4] // size: 5
 * range(4, 5)    ==> [5, 6, 7, 8]  // size: 4, starting from: 5
 * range(4, 5, 2) ==> [5, 7, 9, 11] // size: 4, starting from: 5, step: 2
 * range([2, 5]) ==> [2, 3, 4] // [2, 5) // from: 2 (inclusive), to: 5 (exclusive)
 * range([1, 6], 2) ==> [1, 3, 5] // from: 1, to: 6, step: 2
 * range([1, 7], 2) ==> [1, 3, 5] // from: 1, to: 7 (exclusive), step: 2
 * @see {@link https://stackoverflow.com/a/72388871/5318303}
 */
export function range (sizeOrRange, fromOrStep, stepOrNothing) {
  let from, to, step, size
  if (sizeOrRange instanceof Array) { // 2nd signature: `range([from, to], step)`
    [from, to] = sizeOrRange
    step = fromOrStep ?? 1
    size = Math.ceil((to - from) / step)
  } else { // 1st signature: `range(size, from, step)`
    size = sizeOrRange
    from = fromOrStep ?? 0
    step = stepOrNothing ?? 1
  }
  return Array.from({length: size}, (_, i) => from + i * step)
}

示例:

控制台日志(范围(5),//[0,1,2,3,4]//size:5范围([2,5]),//[2,3,4]//[2、5)//从:2(含)到:5(不含)范围(4,2),//[2,3,4,5]//大小:4,从:2开始范围([1,6],2),//[1,3,5]//从:1到:6,步骤:2范围([1,7],2),//[1,3,5]//从:1到:7(不含),步骤:2)<脚本>函数范围(sizeOrRange、fromOrStep、stepOrNothing){让从、到、步长、大小if(sizeOrRange instanceof Array){//第二个签名:`range([from,to],step)`[from,to]=sizeOrRange步骤=来自或步骤??1.size=数学ceil((to-from)/步长)}else{//第一个签名:`range(大小,从,步)`size=sizeOrRangefrom=来自或步骤??0step=stepOrNothing??1.}return Array.from({length:size},(_,i)=>from+i*step)}</script>