在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
这是我模仿Python的解决方案。在底部,您可以找到一些如何使用它的示例。它与数字一起工作,就像Python的范围一样:
var assert = require('assert'); // if you use Node, otherwise remove the asserts
var L = {}; // L, i.e. 'list'
// range(start, end, step)
L.range = function (a, b, c) {
assert(arguments.length >= 1 && arguments.length <= 3);
if (arguments.length === 3) {
assert(c != 0);
}
var li = [],
i,
start, end, step,
up = true; // Increasing or decreasing order? Default: increasing.
if (arguments.length === 1) {
start = 0;
end = a;
step = 1;
}
if (arguments.length === 2) {
start = a;
end = b;
step = 1;
}
if (arguments.length === 3) {
start = a;
end = b;
step = c;
if (c < 0) {
up = false;
}
}
if (up) {
for (i = start; i < end; i += step) {
li.push(i);
}
} else {
for (i = start; i > end; i += step) {
li.push(i);
}
}
return li;
}
示例:
// range
L.range(0) -> []
L.range(1) -> [0]
L.range(2) -> [0, 1]
L.range(5) -> [0, 1, 2, 3, 4]
L.range(1, 5) -> [1, 2, 3, 4]
L.range(6, 4) -> []
L.range(-2, 2) -> [-2, -1, 0, 1]
L.range(1, 5, 1) -> [1, 2, 3, 4]
L.range(0, 10, 2) -> [0, 2, 4, 6, 8]
L.range(10, 2, -1) -> [10, 9, 8, 7, 6, 5, 4, 3]
L.range(10, 2, -2) -> [10, 8, 6, 4]
其他回答
---更新(感谢@lokhmakov简化)---
另一个使用ES6发生器的版本(参见伟大的Paolo Moretti回答ES6发生器):
const RANGE = (x,y) => Array.from((function*(){
while (x <= y) yield x++;
})());
console.log(RANGE(3,7)); // [ 3, 4, 5, 6, 7 ]
或者,如果我们只需要可迭代,那么:
const RANGE_ITER = (x,y) => (function*(){
while (x <= y) yield x++;
})();
for (let n of RANGE_ITER(3,7)){
console.log(n);
}
// 3
// 4
// 5
// 6
// 7
---原始代码为:---
const RANGE = (a,b) => Array.from((function*(x,y){
while (x <= y) yield x++;
})(a,b));
and
const RANGE_ITER = (a,b) => (function*(x,y){
while (x <= y) yield x++;
})(a,b);
函数范围(firstNum,lastNum){let rangeList=[];如果(firstNum>lastNum){return console.error(“第一个数字不能大于最后一个数字”);}让counter=firstNum;while(计数器<=lastNum){rangeList.push(计数器);计数器++;}返回范围列表;}
为了在任何一个给定的数字可能更大的地方工作,我写了这样一个:
function getRange(start, end) {
return Array.from({
length: 1 + Math.abs(end - start)
}, (_, i) => end > start ? start + i : start - i);
}
尚未实施!
使用新的Number.range建议(第1阶段):
[...Number.range(1, 10)]
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
对于行为类似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);
}