在PHP中,您可以。。。
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。
JavaScript本机是否有内置的功能?如果没有,我将如何实施?
在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']
其他回答
使用这个。它创建了一个具有给定数量的值(未定义)的数组,在下面的示例中有100个索引,但它并不相关,因为这里只需要键。它在数组中使用100+1,因为数组始终基于0索引。因此,如果要生成100个值,则索引从0开始;因此最后的值总是99而不是100。
范围(2100);功能范围(开始、结束){console.log([…Array(end+1).keys()].filter(value=>end>=value&&start<=value));}
使用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”]
您可以使用lodash函数.range(10)https://lodash.com/docs#range
https://stackoverflow.com/a/49577331/8784402
带增量/步长
smallest and one-liner[...Array(N)].map((_, i) => from + i * step);
示例和其他备选方案
[...Array(10)].map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Array.from(Array(10)).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
Array(10).fill(0).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Array(10).fill().map((_, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
Range Function
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]
As Iterators
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 loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
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 loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...
带步长/增量的从到
using iteratorsclass 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]
using Generators
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;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined
对于字体
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);
https://stackoverflow.com/a/64599169/8784402
用一行代码生成字符列表
constcharList=(a,z,d=1)=>(a=a.charCodeAt(),z=z.charCodeAt(),[…数组(Math.floor((z-a)/d)+1)].map((_,i)=>String.fromCharCode(a+i*d)));console.log(“从A到G”,charList('A','G'));console.log(“从A到Z,步长/增量为2”,charList('A','Z',2));console.log(“从Z到P的反向顺序”,charList('Z','P',-1));console.log(“从0到5”,charList(“0”,“5”,1));console.log(“从9到5”,charList('9','5',-1));console.log(“从0到8,步骤2”,charList('0','8',2));console.log(“从α到ω”,charList(“α”,“ω”));console.log(“印地语字符来自क 到ह“,charList('क', 'ह'));console.log(“从А到Е的俄语字符”,charList(“А”,“Е”));
For TypeScriptconst 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)
);
};
我的实施
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