在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
Python风格的方式:
range = (start, end, step) => {
let arr = []
for(let n=start;n<end;n+=(step||1)) arr.push(n)
return arr;
}
其他回答
一个可以在任一方向工作的衬垫:
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));
您可以使用以下一行代码使事情简短明了
var启动=4;var端=20;console.log(数组(end-start+1).fill(start).map((x,y)=>x+y));
要紧密复制的类型脚本函数
/**
* 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
}
}
使用Harmony排列运算符和箭头函数:
var range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);
例子:
range(10, 15);
[ 10, 11, 12, 13, 14, 15 ]
Op要求范围,例如范围(3,10),因此可以
[...[...Array(10-3).keys()].map(i => i+3)]
回报
[3, 4, 5, 6, 7, 8, 9]