假设我有以下复选框:

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

为了得到定义我正在寻找的范围边界的两个数字,我使用下面的jQuery:

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

然后,我如何创建一个包含lowEnd和highEnd之间的所有整数的数组,包括lowEnd和highEnd本身?对于这个特定的例子,显然,结果数组将是:

[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]

当前回答

_Array = (length) => Object.keys(Array.from({length}))

//_Array = [0, 1, 2, 3, 4]

其他回答

在下划线中求解

data = [];
_.times( highEnd, function( n ){ data.push( lowEnd ++ ) } );

我的五分钱:

两个方向的整数数组函数。

当range(0,5)变为[0,1,2,3,4,5]时。

范围(5,0)变为[5,4,3,2,1,0]。

基于这个答案。

function range(start, end) {
  const isReverse = (start > end);
  const targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1;
  const arr = new Array(targetLength);
  const b = Array.apply(null, arr);
  const result = b.map((discard, n) => {
    return (isReverse) ? n + end : n + start;
  });

  return (isReverse) ? result.reverse() : result;
}

附注:为了在现实生活中使用,你还应该检查isFinite()和isNaN()的参数。

这里有3个函数,它们应该涵盖了我能想到的一切(包括对其他一些答案中的问题的修复):rangeInt(), range()和between()。在所有情况下都考虑升序和降序。

例子

范围英特()

包括端点并且只处理整数

rangeInt(1, 4)  // [1, 2, 3, 4] Ascending order
rangeInt(5, 2)  // [5, 4, 3, 2] Descending order
rangeInt(4, 4)  // [4]          Singleton set (i.e. not [4, 4])
rangeInt(-1, 1) // [-1, 0, 1]   Mixing positive and negative

range ()

与rangeInt()相同,除了

不限于整数 允许在第三个参数中指定数量的点

range(0, 10, 2)  // [0, 3.333, 6.666, 10] Gets endpoints and 2 points between
range(0, 1.5, 1) // [0, 0.75, 1.5]        Accepts fractions

间()

与range()相同,除了

不包括端点 没有单例集(将返回一个空数组)

between(0, 10, 2) // [3.333, 6.666]
between(-1, -1.5) // [-1.25]
between(4, 4, 99) // []

/**
 * Gets a set of integers that are evenly distributed along a closed interval
 * @param {int} begin - Beginning endpoint (inclusive)
 * @param {int} end   - Ending endpoint (inclusive)
 * @return {Array} Range of integers
 */
function rangeInt( begin, end )  {
    if ( !Number.isInteger(begin) || !Number.isInteger(end) ) {
        throw new Error('All arguments must be integers')
    }
    return range(begin, end, Math.abs(end - begin) - 1)
}

/**
 * Gets a set of numbers that are evenly distributed along a closed interval
 * @param {Number} begin  - Beginning endpoint (inclusive)
 * @param {Number} end    - Ending endpoint (inclusive)
 * @param {int}    points - How many numbers to retrieve from the open interval
 * @return {Array} Range of numbers
 */
function range( begin, end, points ) {
    if ( begin !== end ) {
        return [ begin, ...between(begin, end, points), end ]
    }
    else if ( Number.isFinite(begin) ) {
        return [ begin ] // singleton set
    }
    else throw new Error('Endpoints must be finite')
}

/**
 * Gets a subset of numbers that are evenly distributed along an open interval
 * @param {Number} begin  - Beginning endpoint (exclusive)
 * @param {Number} end    - Ending endpoint (exclusive)
 * @param {int}    points - How many numbers to retrieve from the interval
 * @return {Array} Retrieved numbers
 */
function between( begin, end, points = 1 ) {
    if ( !Number.isFinite(begin) || !Number.isFinite(end) || !Number.isFinite(points) ) {
        throw new Error('All arguments must be finite')
    }
    const set = []
    // Skip if an open interval does not exist
    if ( begin !== end ) {
        const step = (end - begin) / (points + 1)
        for ( let i = 0; i < points; i++ ) {
            set[i] = begin + (i + 1) * step
        }
    }
    return set
}
var values = $(this).val().split('-'),
    i = +values[0],
    l = +values[1],
    range = [];

while (i < l) {
    range[range.length] = i;
    i += 1;
}

range[range.length] = l;

可能有一个烘干机的方式来做循环,但这是基本的想法。

如果开始总是小于结束,我们可以这样做:

function range(start, end) {
  var myArray = [];
  for (var i = start; i <= end; i += 1) {
    myArray.push(i);
  }
  return myArray;
};
console.log(range(4, 12));                 // → [4, 5, 6, 7, 8, 9, 10, 11, 12]

如果我们希望能够使用第三个参数来修改用于构建数组的步骤,并且即使开始值大于结束值也能使其工作:

function otherRange(start, end, step) {
  otherArray = [];
  if (step == undefined) {
    step = 1;
  };
  if (step > 0) {
    for (var i = start; i <= end; i += step) {
      otherArray.push(i);
    }
  } else {
    for (var i = start; i >= end; i += step) {
      otherArray.push(i);
    }
  };
  return otherArray;
};
console.log(otherRange(10, 0, -2));        // → [10, 8, 6, 4, 2, 0]
console.log(otherRange(10, 15));           // → [10, 11, 12, 13, 14, 15]
console.log(otherRange(10, 20, 2));        // → [10, 12, 14, 16, 18, 20]

这样,函数接受正步长和负步长,如果没有给出步长,则默认为1。