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;
}
var range = function(begin, end) {if (typeof end === "undefined") {end = begin; begin = 0;}var result = [], modifier = end > begin ? 1 : -1;for ( var i = 0; i <= Math.abs(end - begin); i++ ) {result.push(begin + i * modifier);}return result;}
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;}
const range = (start, end) => {let all = [];if (typeof start === "string" && typeof end === "string") {// Return the range of characters using utf-8 least to greatestconst s = start.charCodeAt(0);const e = end.charCodeAt(0);for (let i = s; i <= e; i++) {all.push(String.fromCharCode(i));}} else if (typeof start === "number" && typeof end === "number") {// Return the range of numbers from least to greatestfor(let i = end; i >= start; i--) {all.push(i);}} else {throw new Error("Did not supply matching types number or string.");}return all;}// usageconst aTod = range("a", "d");
如果你喜欢打字稿
const range = (start: string | number, end: string | number): string[] | number[] => {const all: string[] | number[] = [];if (typeof start === "string" && typeof end === "string") {const s: number = start.charCodeAt(0);const e: number = end.charCodeAt(0);for (let i = s; i <= e; i++) {all.push(String.fromCharCode(i));}} else if (typeof start === "number" && typeof end === "number") {for (let i = end; i >= start; i--) {all.push(i);}} else {throw new Error("Did not supply matching types number or string.");}return all;}// Usageconst negTenToten: number[] = range(-10, 10) as number[];
const range = ( a , b ) => Array.from( new Array( b > a ? b - a : a - b ), ( x, i ) => b > a ? i + a : a - i );
range( -3, 2 ); // [ -3, -2, -1, 0, 1 ]range( 1, -4 ); // [ 1, 0, -1, -2, -3 ]
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] = fromstep = step || 1while (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(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
const range = (from, to, step) =>[...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
range(0, 9, 2);//=> [0, 2, 4, 6, 8]
// can also assign range function as static method in Array class (but not recommended )Array.range = (from, to, step) =>[...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
Array.range(2, 10, 2);//=> [2, 4, 6, 8, 10]
Array.range(0, 10, 1);//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array.range(2, 10, -1);//=> []
Array.range(3, 0, -1);//=> [3, 2, 1, 0]
作为迭代器
class Range {constructor(total = 0, step = 1, from = 0) {this[Symbol.iterator] = function* () {for (let i = 0; i < total; yield from + i++ * step) {}};}}
[...new Range(5)]; // Five Elements//=> [0, 1, 2, 3, 4][...new Range(5, 2)]; // Five Elements With Step 2//=> [0, 2, 4, 6, 8][...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10//=>[10, 8, 6, 4, 2][...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10//=> [-10, -12, -14, -16, -18]
// Also works with for..of loopfor (i of new Range(5, -2, 10)) console.log(i);// 10 8 6 4 2
仅作为发电机
const Range = function* (total = 0, step = 1, from = 0) {for (let i = 0; i < total; yield from + i++ * step) {}};
Array.from(Range(5, -2, -10));//=> [-10, -12, -14, -16, -18]
[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10//=> [-10, -12, -14, -16, -18]
// Also works with for..of loopfor (i of Range(5, -2, 10)) console.log(i);// 10 8 6 4 2
// Lazy loaded wayconst number0toInf = Range(Infinity);number0toInf.next().value;//=> 0number0toInf.next().value;//=> 1// ...
从到带步骤/增量
使用迭代器
class Range2 {constructor(to = 0, step = 1, from = 0) {this[Symbol.iterator] = function* () {let i = 0,length = Math.floor((to - from) / step) + 1;while (i < length) yield from + i++ * step;};}}[...new Range2(5)]; // First 5 Whole Numbers//=> [0, 1, 2, 3, 4, 5]
[...new Range2(5, 2)]; // From 0 to 5 with step 2//=> [0, 2, 4]
[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2//=> [10, 8, 6]
使用发电机
const Range2 = function* (to = 0, step = 1, from = 0) {let i = 0,length = Math.floor((to - from) / step) + 1;while (i < length) yield from + i++ * step;};
[...Range2(5, -2, 10)]; // From 10 to 5 with step -2//=> [10, 8, 6]
let even4to10 = Range2(10, 2, 4);even4to10.next().value;//=> 4even4to10.next().value;//=> 6even4to10.next().value;//=> 8even4to10.next().value;//=> 10even4to10.next().value;//=> undefined
对于TypeScript
class _Array<T> extends Array<T> {static range(from: number, to: number, step: number): number[] {return Array.from(Array(Math.floor((to - from) / step) + 1)).map((v, k) => from + k * step);}}_Array.range(0, 9, 1);
const charList = (a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[...Array(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));
console.log("from A to G", charList('A', 'G'));console.log("from A to Z with step/delta of 2", charList('A', 'Z', 2));console.log("reverse order from Z to P", charList('Z', 'P', -1));console.log("from 0 to 5", charList('0', '5', 1));console.log("from 9 to 5", charList('9', '5', -1));console.log("from 0 to 8 with step 2", charList('0', '8', 2));console.log("from α to ω", charList('α', 'ω'));console.log("Hindi characters from क to ह", charList('क', 'ह'));console.log("Russian characters from А to Я", charList('А', 'Я'));
对于TypeScript
const charList = (p: string, q: string, d = 1) => {const a = p.charCodeAt(0),z = q.charCodeAt(0);return [...Array(Math.floor((z - a) / d) + 1)].map((_, i) =>String.fromCharCode(a + i * d));};
function range(firstNum, lastNum) {let rangeList = [];if (firstNum > lastNum) {return console.error("First number cannot be bigger than last number");}
let counter = firstNum;while(counter <= lastNum) {rangeList.push(counter);counter++;}
return rangeList;}
/*** 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}}