在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
---更新(感谢@lokhmakov简化)---
另一个使用ES6发生器的版本(参见伟大的Paolo Moretti回答ES6发生器):
const RANGE = (x,y) => Array.from((function*(){
while (x <= y) yield x++;
})());
console.log(RANGE(3,7)); // [ 3, 4, 5, 6, 7 ]
或者,如果我们只需要可迭代,那么:
const RANGE_ITER = (x,y) => (function*(){
while (x <= y) yield x++;
})();
for (let n of RANGE_ITER(3,7)){
console.log(n);
}
// 3
// 4
// 5
// 6
// 7
---原始代码为:---
const RANGE = (a,b) => Array.from((function*(x,y){
while (x <= y) yield x++;
})(a,b));
and
const RANGE_ITER = (a,b) => (function*(x,y){
while (x <= y) yield x++;
})(a,b);
其他回答
我正在分享我的实现,以防它对某人有所帮助。
function Range(start_or_num, end = null, increment = 1) {
const end_check = end === null
const start = end_check ? 0 : start_or_num
const count = end_check ? start_or_num : Math.round((end - start) / increment) + 1
const filterFunc = end_check ? x => x >= start : x => x < end && x >= start
return [...Array.from(
Array(count).keys(), x => increment * (x - 1) + start
)
].filter(filterFunc)
}
// usage
// console.log(Range(4, 10, 2)) // [4, 6, 8]
// console.log(Range(5, 10 )) //[5, 6, 7, 8, 9]
// console.log(Range(10 ))// [0, 1, 2, 3, 4, 5, 6, 7, 8]
Op要求范围,例如范围(3,10),因此可以
[...[...Array(10-3).keys()].map(i => i+3)]
回报
[3, 4, 5, 6, 7, 8, 9]
Python风格的方式:
range = (start, end, step) => {
let arr = []
for(let n=start;n<end;n+=(step||1)) arr.push(n)
return arr;
}
(from, to) => [...Array(to - from)].map((_,i)=> i + from)
// range() 0..10, step=1
// range(max) 0..max, step=1
// range(min,max) min..max, step=1
// range(min,step,max) min..max, step=step
// Use:
// console.log(...range(3));
// Array.from(range(5))
// [...range(100)]
// for (const v of range(1,10)) { ...
function* range(...args) {
let [min, step, max] = {
0: [0, 1, 10],
1: [0, args[0] >= 0 ? 1 : -1, args[0]],
2: [args[0], args[1] >= args[0] ? 1 : -1, args[1]],
3: args,
}[args.length] || [];
if (min === undefined) throw new SyntaxError("Too many arguments");
let x = min;
while (step >= 0 ? x < max : x > max) {
yield x;
x += step
}
}
console.log(...range()); // 0 1 2 3 4 5 6 7 8 9
console.log(...range(3)); // 0 1 2
console.log(...range(2, 5)); // 2 3 4
console.log(...range(5, 2)); // 5 4 3
console.log(...range(3, -3)); // 3 2 1 0 -1 -2
console.log(...range(-3, 3)); // -3 -2 -1 0 1 2
console.log(...range(-5, -2));// -5 -4 -3
console.log(...range(-2, -5));// -2 -3 -4