在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
它适用于字符和数字,通过可选步骤向前或向后移动。
var range = function(start, end, step) {
var range = [];
var typeofStart = typeof start;
var typeofEnd = typeof end;
if (step === 0) {
throw TypeError("Step cannot be zero.");
}
if (typeofStart == "undefined" || typeofEnd == "undefined") {
throw TypeError("Must pass start and end arguments.");
} else if (typeofStart != typeofEnd) {
throw TypeError("Start and end arguments must be of same type.");
}
typeof step == "undefined" && (step = 1);
if (end < start) {
step = -step;
}
if (typeofStart == "number") {
while (step > 0 ? end >= start : end <= start) {
range.push(start);
start += step;
}
} else if (typeofStart == "string") {
if (start.length != 1 || end.length != 1) {
throw TypeError("Only strings with one character are supported.");
}
start = start.charCodeAt(0);
end = end.charCodeAt(0);
while (step > 0 ? end >= start : end <= start) {
range.push(String.fromCharCode(start));
start += step;
}
} else {
throw TypeError("Only string and number types are supported");
}
return range;
}
jsFiddle。
如果扩充本机类型是您的事情,那么将其分配给Array.range。
var范围=函数(开始、结束、步骤){var范围=[];var typeofStart=启动类型;var typeofEnd=结束类型;如果(步骤==0){throw TypeError(“步长不能为零。”);}if(类型开始==“undefined”| |类型结束==“未定义”){throw TypeError(“必须传递开始和结束参数。”);}否则如果(typeofStart!=typeofEnd){throw TypeError(“开始和结束参数必须是相同的类型。”);}步骤类型==“未定义”&&(步骤=1);if(结束<开始){step=-步骤;}if(开始类型==“number”){while(步骤>0?结束>=开始:结束<=开始){范围.推(启动);开始+=步骤;}}否则if(typeofStart==“string”){如果(start.length!=1 | | end.length;=1){throw TypeError(“仅支持带有一个字符的字符串。”);}start=start.charCodeAt(0);end=end.charCodeAt(0);while(步骤>0?结束>=开始:结束<=开始){range.push(String.fromCharCode(开始));开始+=步骤;}}其他{throw TypeError(“仅支持字符串和数字类型”);}返回范围;}console.log(范围(“A”,“Z”,1));console.log(范围(“Z”,“A”,1));console.log(范围(“A”,“Z”,3));console.log(范围(0,25,1));console.log(范围(0,25,5));console.log(范围(20,5,5));
其他回答
也可以使用生成器生成序列。不同之处在于序列中的每个值都是延迟加载的。spread运算符和for为结果工作。星号符号使函数成为生成器。
const range = function*(from,to) {
for(let i = from; i <= to; i++) yield I;
};
[...range(3,5)]// => [3, 4, 5]
使用Harmony生成器,除IE11外,所有浏览器都支持:
var take = function (amount, generator) {
var a = [];
try {
while (amount) {
a.push(generator.next());
amount -= 1;
}
} catch (e) {}
return a;
};
var takeAll = function (gen) {
var a = [],
x;
try {
do {
x = a.push(gen.next());
} while (x);
} catch (e) {}
return a;
};
var range = (function (d) {
var unlimited = (typeof d.to === "undefined");
if (typeof d.from === "undefined") {
d.from = 0;
}
if (typeof d.step === "undefined") {
if (unlimited) {
d.step = 1;
}
} else {
if (typeof d.from !== "string") {
if (d.from < d.to) {
d.step = 1;
} else {
d.step = -1;
}
} else {
if (d.from.charCodeAt(0) < d.to.charCodeAt(0)) {
d.step = 1;
} else {
d.step = -1;
}
}
}
if (typeof d.from === "string") {
for (let i = d.from.charCodeAt(0); (d.step > 0) ? (unlimited ? true : i <= d.to.charCodeAt(0)) : (i >= d.to.charCodeAt(0)); i += d.step) {
yield String.fromCharCode(i);
}
} else {
for (let i = d.from; (d.step > 0) ? (unlimited ? true : i <= d.to) : (i >= d.to); i += d.step) {
yield i;
}
}
});
示例
take
示例1。
尽可能多地索取
take(10,范围({从:100,步骤:5,到:120}))
回报
[100, 105, 110, 115, 120]
示例2。
不需要
take(10,范围({从:100,步骤:5}))
回报
[100, 105, 110, 115, 120, 125, 130, 135, 140, 145]
全部接受
示例3。
来自不必要的
takeAll(范围({到:5}))
回报
[0, 1, 2, 3, 4, 5]
示例4。
takeAll(范围({到:500,步骤:100}))
回报
[0, 100, 200, 300, 400, 500]
示例5。
takeAll(范围({从:“z”到:“a”}))
回报
[“z”、“y”、“x”、“w”、“v”、“u”、“t”、“s”、“r”、“q”、“p”、“o”、“n”、“m”、“l”、“k”、“j”、“i”、“h”、“g”、“f”、“e”、“d”、“c”、“b”、“a”]
简单范围函数:
function range(start, stop, step) {
var a = [start], b = start;
while (b < stop) {
a.push(b += step || 1);
}
return a;
}
要合并BigInt数据类型,可以包括一些检查,以确保所有变量都是相同的开始类型:
function range(start, stop, step) {
var a = [start], b = start;
if (typeof start == 'bigint') {
stop = BigInt(stop)
step = step? BigInt(step): 1n;
} else
step = step || 1;
while (b < stop) {
a.push(b += step);
}
return a;
}
要删除高于停止定义的值,例如范围(0,5,2)将包括6,但不应是。
function range(start, stop, step) {
var a = [start], b = start;
while (b < stop) {
a.push(b += step || 1);
}
return (b > stop) ? a.slice(0,-1) : a;
}
保持简单:
// Generator
function* iter(a, b, step = 1) {
for (let i = b ? a : 0; i < (b || a); i += step) {
yield i
}
}
const range = (a, b, step = 1) =>
typeof a === 'string'
? [...iter(a.charCodeAt(), b.charCodeAt() + 1)].map(n => String.fromCharCode(n))
: [...iter(a, b, step)]
range(4) // [0, 1, 2, 3]
range(1, 4) // [1, 2, 3]
range(2, 20, 3) // [2, 5, 8, 11, 14, 17]
range('A', 'C') // ['A', 'B', 'C']
这里有一个npm模块bereich(“bereich”是德语中“范围”的意思)。它利用了现代JavaScript的迭代器,因此您可以以各种方式使用它,例如:
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)) {
// ...
}
它还支持递减范围(通过简单地交换最小值和最大值),并且还支持除1以外的步骤。
免责声明:我是本模块的作者,所以请对我的答案持保留态度。