在PHP中,您可以。。。

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

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

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


当前回答

我的实施

export function stringRange(a: string, b: string) {
    let arr = [a + ''];

    const startPrefix = a.match(/([\D])+/g);
    const endPrefix = b.match(/([\D])+/g);

    if ((startPrefix || endPrefix) && (Array.isArray(startPrefix) && startPrefix[0]) !== (Array.isArray(endPrefix) && endPrefix[0])) {
        throw new Error('Series number does not match');
    }

    const startNum = a.match(/([\d])+/g);
    const endNum = b.match(/([\d])+/g);

    if (!startNum || !endNum) {
        throw new Error('Range is not valid');
    }

    let start = parseInt(startNum[0], 10);
    let end = parseInt(endNum[0], 10);

    if (start > end) {
        throw new Error('Ending value should be lessesr that starting value');
    }

    while (start !== end) {
        start++;
        arr.push(startPrefix ? startPrefix[0] + (start + '').padStart(startNum[0].length, '0') : start + '');

    }

    return arr;
}

样本结果

// console.log(range('0', '10'));
// console.log(range('10', '10')); 
// console.log(range('10', '20'));
// console.log(range('10', '20000'));
// console.log(range('ABC10', 'ABC23'));
// console.log(range('ABC10', 'ABC2300'));
// console.log(range('ABC10', 'ABC09')); --> Failure case
// console.log(range('10', 'ABC23')); --> Failure case
// console.log(range('ABC10', '23')); --> Failure case

其他回答

您可以使用以下一行代码使事情简短明了

var启动=4;var端=20;console.log(数组(end-start+1).fill(start).map((x,y)=>x+y));

在Vue中循环0和长度之间的数字范围:


<div v-for="index in range" />

computed: {
   range () {
        let x = [];

        for (let i = 0; i < this.myLength; i++)
        {
            x.push(i);
        }

        return x;
    }
}
    
// range()              0..10, step=1
// range(max)           0..max, step=1
// range(min,max)       min..max, step=1
// range(min,step,max)  min..max, step=step
// Use:
// console.log(...range(3));
// Array.from(range(5))
// [...range(100)]
// for (const v of range(1,10)) { ... 

function* range(...args) {
    let [min, step, max] = {
        0: [0, 1, 10],
        1: [0, args[0] >= 0 ? 1 : -1, args[0]],
        2: [args[0], args[1] >= args[0] ? 1 : -1, args[1]],
        3: args,
    }[args.length] || [];
    if (min === undefined) throw new SyntaxError("Too many arguments");
    let x = min;
    while (step >= 0 ? x < max : x > max) {
        yield x;
        x += step
    }
}
console.log(...range());      // 0 1 2 3 4 5 6 7 8 9
console.log(...range(3));     // 0 1 2
console.log(...range(2, 5));  // 2 3 4
console.log(...range(5, 2));  // 5 4 3
console.log(...range(3, -3)); // 3 2 1 0 -1 -2
console.log(...range(-3, 3)); // -3 -2 -1 0 1 2
console.log(...range(-5, -2));// -5 -4 -3
console.log(...range(-2, -5));// -2 -3 -4

这里是一个范围函数的定义,它的行为与Python的范围类型完全相同,只是这个函数不是懒惰的。把它变成发电机应该很容易。

范围构造函数的参数必须是数字。如果省略step参数,则默认为1。如果省略了start参数,则默认为0。如果步骤为零,则会引发错误。

range = (start, stop, step=1) => {
    if(step === 0) throw new Error("range() arg 3 must not be zero");

    const noStart = stop == null;
    stop = noStart ? start : stop;
    start = noStart ? 0 : start;
    const length = Math.ceil(((stop - start) / step));

    return Array.from({length}, (_, i) => (i * step) + start);
}

console.log(range(-10, 10, 2));
//output [Array] [-10,-8,-6,-4,-2,0,2,4,6,8]
console.log(range(10));
// [Array] [0,1,2,3,4,5,6,7,8,9]
console.log(3, 12);
// [Array] [3,4,5,6,7,8,9,10,11]

我刚刚通过Object.defineProperty在Array上创建了这个polyfill,以创建整数或字符串的范围。Object.defineProperty是创建polyfills的一种更安全的方法。

更安全的polyfill

if (!Array.range) {
  Object.defineProperty(Array, 'range', {
    value: function (from, to, step) {
      if (typeof from !== 'number' && typeof from !== 'string') {
        throw new TypeError('The first parameter should be a number or a character')
      }

      if (typeof to !== 'number' && typeof to !== 'string') {
        throw new TypeError('The second parameter should be a number or a character')
      }

      var A = []
      if (typeof from === 'number') {
        A[0] = from
        step = step || 1
        while (from + step <= to) {
          A[A.length] = from += step
        }
      } else {
        var s = 'abcdefghijklmnopqrstuvwxyz'
        if (from === from.toUpperCase()) {
          to = to.toUpperCase()
          s = s.toUpperCase()
        }
        s = s.substring(s.indexOf(from), s.indexOf(to) + 1)
        A = s.split('')
      }
      return A
    }
  })
} else {
  var errorMessage = 'DANGER ALERT! Array.range has already been defined on this browser. '
  errorMessage += 'This may lead to unwanted results when Array.range() is executed.'
  console.log(errorMessage)
}

示例

Array.range(1, 3)

// Return: [1, 2, 3]
Array.range(1, 3, 0.5)

// Return: [1, 1.5, 2, 2.5, 3]
Array.range('a', 'c')

// Return: ['a', 'b', 'c']
Array.range('A', 'C')

// Return: ['A', 'B', 'C']
Array.range(null)
Array.range(undefined)
Array.range(NaN)
Array.range(true)
Array.range([])
Array.range({})
Array.range(1, null)

// Return: Uncaught TypeError: The X parameter should be a number or a character