在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
已经给出了非常好的答案,但我没有看到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]
其他回答
保持简单:
// 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']
数字
[...Array(5).keys()];
=> [0, 1, 2, 3, 4]
字符迭代
String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));
=> "ABCD"
迭代
for (const x of Array(5).keys()) {
console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
}
=> 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"
作为函数
function range(size, startAt = 0) {
return [...Array(size).keys()].map(i => i + startAt);
}
function characterRange(startChar, endChar) {
return String.fromCharCode(...range(endChar.charCodeAt(0) -
startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
类型化函数
function range(size:number, startAt:number = 0):ReadonlyArray<number> {
return [...Array(size).keys()].map(i => i + startAt);
}
function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {
return String.fromCharCode(...range(endChar.charCodeAt(0) -
startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
lodash.js_.range()函数
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
=> "ABCD"
没有库的旧非es6浏览器:
Array.apply(null, Array(5)).map(function (_, i) {return i;});
=> [0, 1, 2, 3, 4]
console.log([…Array(5).keys()]);
(ES6归功于尼尔斯·彼得索恩和其他评论者)
Array.range = function(a, b, step){
var A = [];
if(typeof a == 'number'){
A[0] = a;
step = step || 1;
while(a+step <= b){
A[A.length]= a+= step;
}
}
else {
var s = 'abcdefghijklmnopqrstuvwxyz';
if(a === a.toUpperCase()){
b = b.toUpperCase();
s = s.toUpperCase();
}
s = s.substring(s.indexOf(a), s.indexOf(b)+ 1);
A = s.split('');
}
return A;
}
Array.range(0,10);
// [0,1,2,3,4,5,6,7,8,9,10]
Array.range(-100,100,20);
// [-100,-80,-60,-40,-20,0,20,40,60,80,100]
Array.range('A','F');
// ['A','B','C','D','E','F')
Array.range('m','r');
// ['m','n','o','p','q','r']
对于数字,您可以使用ES6 Array.from(),它现在可以在除IE以外的任何情况下工作:
较短版本:
Array.from({length: 20}, (x, i) => i);
更长版本:
Array.from(new Array(20), (x, i) => i);
这创建了从0到19(包括0到19)的数组。这可以进一步简化为以下形式之一:
Array.from(Array(20).keys());
// or
[...Array(20).keys()];
也可以指定下限和上限,例如:
Array.from(new Array(20), (x, i) => i + *lowerBound*);
一篇文章对此进行了更详细的描述:http://www.2ality.com/2014/05/es6-array-methods.html
---更新(感谢@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);