在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
我的实施
export function stringRange(a: string, b: string) {
let arr = [a + ''];
const startPrefix = a.match(/([\D])+/g);
const endPrefix = b.match(/([\D])+/g);
if ((startPrefix || endPrefix) && (Array.isArray(startPrefix) && startPrefix[0]) !== (Array.isArray(endPrefix) && endPrefix[0])) {
throw new Error('Series number does not match');
}
const startNum = a.match(/([\d])+/g);
const endNum = b.match(/([\d])+/g);
if (!startNum || !endNum) {
throw new Error('Range is not valid');
}
let start = parseInt(startNum[0], 10);
let end = parseInt(endNum[0], 10);
if (start > end) {
throw new Error('Ending value should be lessesr that starting value');
}
while (start !== end) {
start++;
arr.push(startPrefix ? startPrefix[0] + (start + '').padStart(startNum[0].length, '0') : start + '');
}
return arr;
}
样本结果
// console.log(range('0', '10'));
// console.log(range('10', '10'));
// console.log(range('10', '20'));
// console.log(range('10', '20000'));
// console.log(range('ABC10', 'ABC23'));
// console.log(range('ABC10', 'ABC2300'));
// console.log(range('ABC10', 'ABC09')); --> Failure case
// console.log(range('10', 'ABC23')); --> Failure case
// console.log(range('ABC10', '23')); --> Failure case
其他回答
可以如下创建大量使用ES6的相当简约的实现,特别注意Array.from()静态方法:
const getRange = (start, stop) => Array.from(
new Array((stop - start) + 1),
(_, i) => i + start
);
下面是实现自己的可迭代范围函数的方法。
//实施范围功能范围(开始、结束){返回{从:开始,结束,[Symbol.iiterator](){this.current=this.from;返回此;},next(){if(this.current<=this.to){返回{done:false,值:this.current++};}其他{返回{done:true};}}};}//迭代每个值for(设范围数(1,5)){console.log(num);//1, 2, 3, 4, 5}
为了在任何一个给定的数字可能更大的地方工作,我写了这样一个:
function getRange(start, end) {
return Array.from({
length: 1 + Math.abs(end - start)
}, (_, i) => end > start ? start + i : start - i);
}
虽然这不是来自PHP,而是对Python范围的模仿。
function range(start, end) {
var total = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i += 1) {
total.push(i);
}
return total;
}
console.log(range(10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(range(0, 10)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(range(5, 10)); // [5, 6, 7, 8, 9]
编码为2010年规格(是的,2016年是ES6发电机)。这是我的想法,其中包含模拟Python的range()函数的选项。
Array.range = function(start, end, step){
if (start == undefined) { return [] } // "undefined" check
if ( (step === 0) ) { return []; // vs. throw TypeError("Invalid 'step' input")
} // "step" == 0 check
if (typeof start == 'number') { // number check
if (typeof end == 'undefined') { // single argument input
end = start;
start = 0;
step = 1;
}
if ((!step) || (typeof step != 'number')) {
step = end < start ? -1 : 1;
}
var length = Math.max(Math.ceil((end - start) / step), 0);
var out = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
out[idx] = start;
}
// Uncomment to check "end" in range() output, non pythonic
if ( (out[out.length-1] + step) == end ) { // "end" check
out.push(end)
}
} else {
// Historical: '&' is the 27th letter: http://nowiknow.com/and-the-27th-letter-of-the-alphabet/
// Axiom: 'a' < 'z' and 'z' < 'A'
// note: 'a' > 'A' == true ("small a > big A", try explaining it to a kid! )
var st = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&'; // axiom ordering
if (typeof end == 'undefined') { // single argument input
end = start;
start = 'a';
}
var first = st.indexOf(start);
var last = st.indexOf(end);
if ((!step) || (typeof step != 'number')) {
step = last < first ? -1 : 1;
}
if ((first == -1) || (last == -1 )) { // check 'first' & 'last'
return []
}
var length = Math.max(Math.ceil((last - first) / step), 0);
var out = Array(length);
for (var idx = 0; idx < length; idx++, first += step) {
out[idx] = st[first];
}
// Uncomment to check "end" in range() output, non pythonic
if ( (st.indexOf(out[out.length-1]) + step ) == last ) { // "end" check
out.push(end)
}
}
return out;
}
例子:
Array.range(5); // [0,1,2,3,4,5]
Array.range(4,-4,-2); // [4, 2, 0, -2, -4]
Array.range('a','d'); // ["a", "b", "c", "d"]
Array.range('B','y'); // ["B", "A", "z", "y"], different from chr() ordering
Array.range('f'); // ["a", "b", "c", "d", "e", "f"]
Array.range(-5); // [], similar to python
Array.range(-5,0) // [-5,-4-,-3-,-2,-1,0]