在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
保持简单:
// Generator
function* iter(a, b, step = 1) {
for (let i = b ? a : 0; i < (b || a); i += step) {
yield i
}
}
const range = (a, b, step = 1) =>
typeof a === 'string'
? [...iter(a.charCodeAt(), b.charCodeAt() + 1)].map(n => String.fromCharCode(n))
: [...iter(a, b, step)]
range(4) // [0, 1, 2, 3]
range(1, 4) // [1, 2, 3]
range(2, 20, 3) // [2, 5, 8, 11, 14, 17]
range('A', 'C') // ['A', 'B', 'C']
其他回答
我很惊讶地看到了这条线索,并没有看到任何类似我的解决方案(也许我错过了答案),所以就在这里。我在ES6语法中使用了一个简单的范围函数:
// [begin, end[
const range = (b, e) => Array.apply(null, Array(e - b)).map((_, i) => {return i+b;});
但它只在向前计数时有效(即begin<end),因此我们可以在需要时对其进行轻微修改,如下所示:
const range = (b, e) => Array.apply(null, Array(Math.abs(e - b))).map((_, i) => {return b < e ? i+b : b-i;});
/**
* @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>
var range = (l,r) => new Array(r - l).fill().map((_,k) => k + l);
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)
);
};
…更大范围,使用生成器功能。
function range(s, e, str){
// create generator that handles numbers & strings.
function *gen(s, e, str){
while(s <= e){
yield (!str) ? s : str[s]
s++
}
}
if (typeof s === 'string' && !str)
str = 'abcdefghijklmnopqrstuvwxyz'
const from = (!str) ? s : str.indexOf(s)
const to = (!str) ? e : str.indexOf(e)
// use the generator and return.
return [...gen(from, to, str)]
}
// usage ...
console.log(range('l', 'w'))
//=> [ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' ]
console.log(range(7, 12))
//=> [ 7, 8, 9, 10, 11, 12 ]
// first 'o' to first 't' of passed in string.
console.log(range('o', 't', "ssshhhooooouuut!!!!"))
// => [ 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 't' ]
// only lowercase args allowed here, but ...
console.log(range('m', 'v').map(v=>v.toUpperCase()))
//=> [ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' ]
// => and decreasing range ...
console.log(range('m', 'v').map(v=>v.toUpperCase()).reverse())
// => ... and with a step
console.log(range('m', 'v')
.map(v=>v.toUpperCase())
.reverse()
.reduce((acc, c, i) => (i % 2) ? acc.concat(c) : acc, []))
// ... etc, etc.
希望这有用。