在PHP中,您可以。。。

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

也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。

JavaScript本机是否有内置的功能?如果没有,我将如何实施?


当前回答

好的,在JavaScript中,我们没有像PHP那样的range()函数,所以我们需要创建一个非常简单的函数

对于数字:

function numberRange (start, end) {
  return new Array(end - start).fill().map((d, i) => i + start);
}

并将其称为:

numberRange(5, 10); //[5, 6, 7, 8, 9]

对于字母:

function alphabetRange (start, end) {
  return new Array(end.charCodeAt(0) - start.charCodeAt(0)).fill().map((d, i) => String.fromCharCode(i + start.charCodeAt(0)));
}

并将其称为:

alphabetRange('c', 'h'); //["c", "d", "e", "f", "g"]

其他回答

Op要求范围,例如范围(3,10),因此可以

[...[...Array(10-3).keys()].map(i => i+3)]

回报

[3, 4, 5, 6, 7, 8, 9]

我刚刚通过Object.defineProperty在Array上创建了这个polyfill,以创建整数或字符串的范围。Object.defineProperty是创建polyfills的一种更安全的方法。

更安全的polyfill

if (!Array.range) {
  Object.defineProperty(Array, 'range', {
    value: function (from, to, step) {
      if (typeof from !== 'number' && typeof from !== 'string') {
        throw new TypeError('The first parameter should be a number or a character')
      }

      if (typeof to !== 'number' && typeof to !== 'string') {
        throw new TypeError('The second parameter should be a number or a character')
      }

      var A = []
      if (typeof from === 'number') {
        A[0] = from
        step = step || 1
        while (from + step <= to) {
          A[A.length] = from += step
        }
      } else {
        var s = 'abcdefghijklmnopqrstuvwxyz'
        if (from === from.toUpperCase()) {
          to = to.toUpperCase()
          s = s.toUpperCase()
        }
        s = s.substring(s.indexOf(from), s.indexOf(to) + 1)
        A = s.split('')
      }
      return A
    }
  })
} else {
  var errorMessage = 'DANGER ALERT! Array.range has already been defined on this browser. '
  errorMessage += 'This may lead to unwanted results when Array.range() is executed.'
  console.log(errorMessage)
}

示例

Array.range(1, 3)

// Return: [1, 2, 3]
Array.range(1, 3, 0.5)

// Return: [1, 1.5, 2, 2.5, 3]
Array.range('a', 'c')

// Return: ['a', 'b', 'c']
Array.range('A', 'C')

// Return: ['A', 'B', 'C']
Array.range(null)
Array.range(undefined)
Array.range(NaN)
Array.range(true)
Array.range([])
Array.range({})
Array.range(1, null)

// Return: Uncaught TypeError: The X parameter should be a number or a character

对于行为类似python range()函数的函数,请使用以下命令:

function range(min=0, max=null){
    if(max === null){
        max=min;
        min=0;
    }
    var rg=[...Array(max).keys()];
    return rg.slice(min,max);
}   

使用这个。它创建了一个具有给定数量的值(未定义)的数组,在下面的示例中有100个索引,但它并不相关,因为这里只需要键。它在数组中使用100+1,因为数组始终基于0索引。因此,如果要生成100个值,则索引从0开始;因此最后的值总是99而不是100。

范围(2100);功能范围(开始、结束){console.log([…Array(end+1).keys()].filter(value=>end>=value&&start<=value));}

对于字母,他是我想出的一个生成字母范围的简单JS解决方案。它只用于生成大写或小写字母的数组。

功能范围(第一个,最后一个){var r=[],i=first.charCodeAt(0);而(i<=last.charCodeAt(0)){r.push(String.fromCharCode(i++));}返回r;}console.dir(范围(“a”,“f”));console.dir(范围(“G”,“Z”));