Create array of all integers between two numbers,

2020-02-02 04:11发布

Say I have the following checkbox:

<input type="checkbox" value="1-25" />

To get the two numbers that define the boundaries of range I'm looking for, I use the following jQuery:

var value = $(this).val();
var lowEnd = Number(value.split('-')[0]);
var highEnd = Number(value.split('-')[1]);

How do I then create an array that contains all integers between lowEnd and highEnd, including lowEnd and highEnd themselves? For this specific example, obviously, the resulting array would be:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

15条回答
做自己的国王
2楼-- · 2020-02-02 04:43

My version of the loop ;)

var lowEnd = 1;
var highEnd = 25;
var arr = [];
while(lowEnd <= highEnd){
   arr.push(lowEnd++);
}
查看更多
孤傲高冷的网名
3楼-- · 2020-02-02 04:50

In JavaScript ES6:

function range(start, end) {
  return Array(end - start + 1).fill().map((_, idx) => start + idx)
}
var result = range(9, 18); // [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
console.log(result);

For completeness, here it is with an optional step parameter.

function range(start, end, step = 1) {
  const len = Math.floor((end - start) / step) + 1
  return Array(len).fill().map((_, idx) => start + (idx * step))
}
var result = range(9, 18, 0.83);
console.log(result);

I would use range-inclusive from npm in an actual project. It even supports backwards steps, so that's cool.

查看更多
可以哭但决不认输i
4楼-- · 2020-02-02 04:51
var list = [];
for (var i = lowEnd; i <= highEnd; i++) {
    list.push(i);
}
查看更多
登录 后发表回答