在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的范围类型完全相同,只是这个函数不是懒惰的。把它变成发电机应该很容易。
范围构造函数的参数必须是数字。如果省略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]
其他回答
使用范围([start,]stop[,step])签名完成ES6实现:
function range(start, stop, step=1){
if(!stop){stop=start;start=0;}
return Array.from(new Array(int((stop-start)/step)), (x,i) => start+ i*step)
}
如果要自动负步进,请添加
if(stop<start)step=-Math.abs(step)
或者更简单地说:
range=(b, e, step=1)=>{
if(!e){e=b;b=0}
return Array.from(new Array(int((e-b)/step)), (_,i) => b<e? b+i*step : b-i*step)
}
如果你有巨大的射程,看看保罗·莫雷蒂的发电机方法
对于行为类似python range()函数的函数,请使用以下命令:
function range(min=0, max=null){
if(max === null){
max=min;
min=0;
}
var rg=[...Array(max).keys()];
return rg.slice(min,max);
}
为了在任何一个给定的数字可能更大的地方工作,我写了这样一个:
function getRange(start, end) {
return Array.from({
length: 1 + Math.abs(end - start)
}, (_, i) => end > start ? start + i : start - i);
}
这里有一个基于@benmcdonald和其他人的简单方法,尽管不止一行。。。
设K=[];对于(i=“A”.charCodeAt(0);i<=“Z”.charCodeAt(0);i++){K.push(字符串来自CharCode(i))};console.log(K);
已经给出了非常好的答案,但我没有看到ES6迭代器的完整使用来实现范围的完整实现,所以这里是:
/**
* inspired by Python's built-in range utility function
* implemented using ES6 Iterable, Iterator protolols (interfaces)
*/
class Range {
constructor(...args) {
this.start = args.length <= 1 ? 0 : args[0];
this.end = args.length <= 1 ? args[0] || 0 : args[1];
this.step = args.length <= 2 ? 1 : args[2];
}
[Symbol.iterator]() {
return this;
}
next() {
if (this.end > this.start) {
const result = { done: false, value: this.start };
this.start = this.start + this.step;
return result;
} else return { done: true, value: undefined };
}
}
/**
* Symbol.iterator is part of the couple of inbuilt symbols
* available in JavaScript. It allows for hooking into the
* inbuilt for of iteration mechanism. This is why the
* Symbol.iterator comes into play when talking about
* iterables and iterators in JavaScript.
*/
function range(...args) {
return new Range(...args);
}
console.log([...range(4)]); // [0, 1, 2, 3]
console.log([...range(2, 5)]); // [2, 3, 4]
console.log([...range(1, 10, 3)]); // [1, 4, 7]