在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
我回顾了这里的答案,并注意到以下几点:
JavaScript没有解决此问题的内置解决方案某些答案生成大小正确但值错误的数组例如,让arr=Array.from({length:3});//给出[null,null,null]然后,使用映射函数将错误的值替换为正确的值例如arr.map((e,i)=>i);//给出[0,1,2]需要数学来移动数字范围,以满足从。。符合要求。例如arr.map((e,i)=>i+1);//给出[1,2,3]对于问题的字符串版本,需要charCodeAt和fromCharCode将字符串映射到一个数字,然后再返回到一个字符串。例如arr.map((e,i)=>String.fromCharCode(i+“A”.charCodeAt(0));//给出[“A”、“B”、“C”]
有一些基于以上部分或全部的简单到花哨的实现。当他们试图将整数和字符串解打包到一个函数中时,答案变得复杂起来。对我来说,我选择在它们自己的函数中实现整数和字符串解决方案。我证明这是合理的,因为在实践中,你会知道你的用例是什么,你会直接使用适当的函数。如果您想间接调用包装器函数,我也会提供它。
让rangeInt=(from,to)=>Array.from({length:to from+1},(e,i)=>i+from);let rangeChar=(from,to)=>数组.from({length:to.charCodeAt(0)-from.charCodeAt(0)+1},(e,i)=>字符串.fromCharCode(i+from.charCode At(1)));让范围=(从,到)=>(typeof(from)==“string”&&typeof(to)===“string”)? rangeChar(从,到):(!to)?rangeInt(0,from-1):范围Int(从,到);console.log(rangeInt(1,3));//给出[1,2,3]console.log(rangeChar(“A”,“C”));//给出[“A”、“B”、“C”]console.log(范围(1,3));//给出[1,2,3]console.log(范围(“A”、“C”));//给出[“A”、“B”、“C”]console.log(范围(3));//给出[0,1,2]
其他回答
这里有一个很好的简单方法,可以在ES6中只使用数字(不知道它的速度比较):
Array.prototype.map.call(' '.repeat(1 + upper - lower), (v, i) => i + lower)
对于单个字符的范围,可以稍微修改一下:
Array.prototype.map.call(' '.repeat(1 + upper.codePointAt() - lower.codePointAt()), (v, i) => String.fromCodePoint(i + lower.codePointAt()));
这里是一个范围函数的定义,它的行为与Python的范围类型完全相同,只是这个函数不是懒惰的。把它变成发电机应该很容易。
范围构造函数的参数必须是数字。如果省略step参数,则默认为1。如果省略了start参数,则默认为0。如果步骤为零,则会引发错误。
range = (start, stop, step=1) => {
if(step === 0) throw new Error("range() arg 3 must not be zero");
const noStart = stop == null;
stop = noStart ? start : stop;
start = noStart ? 0 : start;
const length = Math.ceil(((stop - start) / step));
return Array.from({length}, (_, i) => (i * step) + start);
}
console.log(range(-10, 10, 2));
//output [Array] [-10,-8,-6,-4,-2,0,2,4,6,8]
console.log(range(10));
// [Array] [0,1,2,3,4,5,6,7,8,9]
console.log(3, 12);
// [Array] [3,4,5,6,7,8,9,10,11]
范围(开始、结束、步骤):使用ES6迭代器
你只要求上限和下限。在这里,我们也创建了一个带步骤的。
您可以轻松创建range()生成器函数,该函数可以用作迭代器。这意味着您不必预先生成整个阵列。
function * range ( start, end, step = 1 ) {
let state = start;
while ( state < end ) {
yield state;
state += step;
}
return;
};
现在,您可能需要创建一个从迭代器预生成数组并返回列表的东西。这对于接受数组的函数很有用。为此,我们可以使用Array.from()
const generate_array = (start,end,step) =>
Array.from( range(start,end,step) );
现在您可以轻松生成静态数组,
const array1 = generate_array(1,10,2);
const array1 = generate_array(1,7);
但是,当需要迭代器(或允许您使用迭代器)时,您也可以轻松创建迭代器。
for ( const i of range(1, Number.MAX_SAFE_INTEGER, 7) ) {
console.log(i)
}
特别注意事项
如果你使用Ramda,他们和Lodash一样有自己的R.range
/**
* @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>
要紧密复制的类型脚本函数
/**
* 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
}
}