在PHP中,您可以。。。

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

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

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


当前回答

已经给出了非常好的答案,但我没有看到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]

其他回答

一个可以在任一方向工作的衬垫:

const range = (a,b)=>Array(Math.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));

请参阅实际操作:

常量范围=(a,b)=>数组(数学.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));console.log(范围(1,4));console.log(范围(4,1));

Op要求范围,例如范围(3,10),因此可以

[...[...Array(10-3).keys()].map(i => i+3)]

回报

[3, 4, 5, 6, 7, 8, 9]

使用Harmony生成器,除IE11外,所有浏览器都支持:

var take = function (amount, generator) {
    var a = [];

    try {
        while (amount) {
            a.push(generator.next());
            amount -= 1;
        }
    } catch (e) {}

    return a;
};

var takeAll = function (gen) {
    var a = [],
        x;

    try {
        do {
            x = a.push(gen.next());
        } while (x);
    } catch (e) {}

    return a;
};

var range = (function (d) {
    var unlimited = (typeof d.to === "undefined");

    if (typeof d.from === "undefined") {
        d.from = 0;
    }

    if (typeof d.step === "undefined") {
        if (unlimited) {
            d.step = 1;
        }
    } else {
        if (typeof d.from !== "string") {
            if (d.from < d.to) {
                d.step = 1;
            } else {
                d.step = -1;
            }
        } else {
            if (d.from.charCodeAt(0) < d.to.charCodeAt(0)) {
                d.step = 1;
            } else {
                d.step = -1;
            }
        }
    }

    if (typeof d.from === "string") {
        for (let i = d.from.charCodeAt(0); (d.step > 0) ? (unlimited ? true : i <= d.to.charCodeAt(0)) : (i >= d.to.charCodeAt(0)); i += d.step) {
            yield String.fromCharCode(i);
        }
    } else {
        for (let i = d.from; (d.step > 0) ? (unlimited ? true : i <= d.to) : (i >= d.to); i += d.step) {
            yield i;
        }
    }
});

示例

take

示例1。

尽可能多地索取

take(10,范围({从:100,步骤:5,到:120}))

回报

[100, 105, 110, 115, 120]

示例2。

不需要

take(10,范围({从:100,步骤:5}))

回报

[100, 105, 110, 115, 120, 125, 130, 135, 140, 145]

全部接受

示例3。

来自不必要的

takeAll(范围({到:5}))

回报

[0, 1, 2, 3, 4, 5]

示例4。

takeAll(范围({到:500,步骤:100}))

回报

[0, 100, 200, 300, 400, 500]

示例5。

takeAll(范围({从:“z”到:“a”}))

回报

[“z”、“y”、“x”、“w”、“v”、“u”、“t”、“s”、“r”、“q”、“p”、“o”、“n”、“m”、“l”、“k”、“j”、“i”、“h”、“g”、“f”、“e”、“d”、“c”、“b”、“a”]

在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;
    }
}
    

简单范围函数:

function range(start, stop, step) {
    var a = [start], b = start;
    while (b < stop) {
        a.push(b += step || 1);
    }
    return a;
}

要合并BigInt数据类型,可以包括一些检查,以确保所有变量都是相同的开始类型:

function range(start, stop, step) {
    var a = [start], b = start;
    if (typeof start == 'bigint') {
        stop = BigInt(stop)
        step = step? BigInt(step): 1n;
    } else
        step = step || 1;
    while (b < stop) {
        a.push(b += step);
    }
    return a;
}

要删除高于停止定义的值,例如范围(0,5,2)将包括6,但不应是。

function range(start, stop, step) {
    var a = [start], b = start;
    while (b < stop) {
        a.push(b += step || 1);
    }
    return (b > stop) ? a.slice(0,-1) : a;
}