Does JavaScript have a method like “range()” to ge

2018-12-31 06:25发布

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")

That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.

Is there anything built-in to JavaScript natively for this? If not, how would I implement it?

30条回答
残风、尘缘若梦
2楼-- · 2018-12-31 07:26

Using Harmony spread operator and arrow functions:

var range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);

Example:

range(10, 15);
[ 10, 11, 12, 13, 14, 15 ]
查看更多
与风俱净
3楼-- · 2018-12-31 07:26

There's an npm module bereich for that ("bereich" is the German word for "range"). It makes use of modern JavaScript's iterators, so you can use it in various ways, such as:

console.log(...bereich(1, 10));
// => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

const numbers = Array.from(bereich(1, 10));
// => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

for (const number of bereich(1, 10)) {
  // ...
}

It also supports descending ranges (by simply exchanging min and max), and it also supports steps other than 1.

Disclaimer: I am the author of this module, so please take my answer with a grain of salt.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 07:27

The standard Javascript doesn't have a built-in function to generate ranges. Several javascript frameworks add support for such features, or as others have pointed out you can always roll your own.

If you'd like to double-check, the definitive resource is the ECMA-262 Standard.

查看更多
只若初见
5楼-- · 2018-12-31 07:27

d3 also has a built-in range function. See https://github.com/mbostock/d3/wiki/Arrays#d3_range:

d3.range([start, ]stop[, step])

Generates an array containing an arithmetic progression, similar to the Python built-in range. This method is often used to iterate over a sequence of numeric or integer values, such as the indexes into an array. Unlike the Python version, the arguments are not required to be integers, though the results are more predictable if they are due to floating point precision. If step is omitted, it defaults to 1.

Example:

d3.range(10)
// returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
查看更多
长期被迫恋爱
6楼-- · 2018-12-31 07:28

A rather minimalistic implementation that heavily employs ES6 can be created as follows, drawing particular attention to the Array.from() static method:

const getRange = (start, stop) => Array.from(
  new Array((stop - start) + 1),
  (_, i) => i + start
);
查看更多
其实,你不懂
7楼-- · 2018-12-31 07:30

Here's a nice short way to do it in ES6 with numbers only (don't know its speed compares):

Array.prototype.map.call(' '.repeat(1 + upper - lower), (v, i) => i + lower)

For a range of single characters, you can slightly modify it:

Array.prototype.map.call(' '.repeat(1 + upper.codePointAt() - lower.codePointAt()), (v, i) => String.fromCodePoint(i + lower.codePointAt()));
查看更多
登录 后发表回答