JavaScript的是否有像&QUOT的方法;)范围内(QUOT;生成基于界提供一个数组? [英] Does JavaScript have a method like "range()" to generate an array based on supplied bounds?
本文介绍了JavaScript的是否有像&QUOT的方法;)范围内(QUOT;生成基于界提供一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP中,你可以做...
In PHP, you can do...
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
即,有可让您通过将上限和下限获得一系列数字或字符的函数。
That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.
有没有内置的JavaScript来为本身这样的东西?如果没有,我将如何实现呢?
Is there anything built-in to JavaScript natively for this? If not, how would I implement it?
推荐答案
它适用于字符和数字,有一个可选的步骤前进或倒退。
It works for characters and numbers, going forwards or backwards with an optional step.
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;
}
如果充实本地类型是你的事,然后将其分配给 Array.range
。
If augmenting native types is your thing, then assign it to Array.range
.
这篇关于JavaScript的是否有像&QUOT的方法;)范围内(QUOT;生成基于界提供一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文