在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]
其他回答
为了在任何一个给定的数字可能更大的地方工作,我写了这样一个:
function getRange(start, end) {
return Array.from({
length: 1 + Math.abs(end - start)
}, (_, i) => end > start ? start + i : start - i);
}
这个也反过来。
const range = ( a , b ) => Array.from( new Array( b > a ? b - a : a - b ), ( x, i ) => b > a ? i + a : a - i );
range( -3, 2 ); // [ -3, -2, -1, 0, 1 ]
range( 1, -4 ); // [ 1, 0, -1, -2, -3 ]
如果在Visual Studio代码中遇到以下错误:
类型“IterableIterator”不是数组类型或字符串类型。使用编译器选项“--downloadIteration”允许迭代迭代器。
而不是
[...Array(3).keys()]
你可以信赖
Array.from(Array(3).keys())
有关下层迭代的更多信息
在Vue中循环0和长度之间的数字范围:
<div v-for="index in range" />
computed: {
range () {
let x = [];
for (let i = 0; i < this.myLength; i++)
{
x.push(i);
}
return x;
}
}
范围(开始、结束、步骤):使用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