在PHP中,您可以。。。

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

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

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


当前回答

对于字母,他是我想出的一个生成字母范围的简单JS解决方案。它只用于生成大写或小写字母的数组。

功能范围(第一个,最后一个){var r=[],i=first.charCodeAt(0);而(i<=last.charCodeAt(0)){r.push(String.fromCharCode(i++));}返回r;}console.dir(范围(“a”,“f”));console.dir(范围(“G”,“Z”));

其他回答

我的代码高尔夫同事想出了这个(ES6),包容的:

(s,f)=>[...Array(f-s+1)].map((e,i)=>i+s)

非包容性:

(s,f)=>[...Array(f-s)].map((e,i)=>i+s)
/**
 * @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>

Javascript提供了一个从给定值创建和填充数组的函数,接收容器数组和映射函数作为参数:

让arr=数组来源(SOURCE_Array,MAP_FUNCTION);

由于MAP_FUNCTION提供了迭代的值和索引,因此可以创建一个空数组(SOURCE_array)并使用索引填充它,如下所示(supposing 10是您所需的长度):

let arr=Array.from(数组(10),(n,索引)=>索引);

输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

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

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

已经给出了非常好的答案,但我没有看到ES6迭代器的完整使用来实现范围的完整实现,所以这里是:

/**
 * inspired by Python's built-in range utility function
 * implemented using ES6 Iterable, Iterator  protolols (interfaces)
 */
class Range {
  constructor(...args) {
    this.start = args.length <= 1 ? 0 : args[0];
    this.end = args.length <= 1 ? args[0] || 0 : args[1];
    this.step = args.length <= 2 ? 1 : args[2];
  }

  [Symbol.iterator]() {
    return this;
  }

  next() {
    if (this.end > this.start) {
      const result = { done: false, value: this.start };
      this.start = this.start + this.step;
      return result;
    } else return { done: true, value: undefined };
  }
}

/**
 * Symbol.iterator is part of the couple of inbuilt symbols
 * available in JavaScript. It allows for hooking into the
 * inbuilt for of iteration mechanism. This is why the
 * Symbol.iterator comes into play when talking about
 * iterables and iterators in JavaScript.
 */

function range(...args) {
  return new Range(...args);
}

console.log([...range(4)]);        // [0, 1, 2, 3]
console.log([...range(2, 5)]);     // [2, 3, 4]
console.log([...range(1, 10, 3)]); // [1, 4, 7]