在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本机是否有内置的功能?如果没有,我将如何实施?
当前回答
使用Harmony排列运算符和箭头函数:
var range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);
例子:
range(10, 15);
[ 10, 11, 12, 13, 14, 15 ]
其他回答
我想补充一点,我认为这是一个非常可调的版本,速度非常快。
const range = (start, end) => {
let all = [];
if (typeof start === "string" && typeof end === "string") {
// Return the range of characters using utf-8 least to greatest
const s = start.charCodeAt(0);
const e = end.charCodeAt(0);
for (let i = s; i <= e; i++) {
all.push(String.fromCharCode(i));
}
} else if (typeof start === "number" && typeof end === "number") {
// Return the range of numbers from least to greatest
for(let i = end; i >= start; i--) {
all.push(i);
}
} else {
throw new Error("Did not supply matching types number or string.");
}
return all;
}
// usage
const aTod = range("a", "d");
如果您愿意,也可以使用打字机
const range = (start: string | number, end: string | number): string[] | number[] => {
const all: string[] | number[] = [];
if (typeof start === "string" && typeof end === "string") {
const s: number = start.charCodeAt(0);
const e: number = end.charCodeAt(0);
for (let i = s; i <= e; i++) {
all.push(String.fromCharCode(i));
}
} else if (typeof start === "number" && typeof end === "number") {
for (let i = end; i >= start; i--) {
all.push(i);
}
} else {
throw new Error("Did not supply matching types number or string.");
}
return all;
}
// Usage
const negTenToten: number[] = range(-10, 10) as number[];
受到其他答案的影响。用户已离开。
这是我用于数字范围的方法:
const rangeFrom0 = end => [...Array(end)].map((_, index) => index);
or
const rangeExcEnd = (start, step, end) => [...Array(end - start + 1)]
.map((_, index) => index + start)
.filter(x => x % step === start % step);
function check(){
var correct=true;
for(var i=0; i<arguments.length; i++){
if(typeof arguments[i] != "number"){
correct=false; } } return correct; }
//------------------------------------------
function range(start,step,end){
var correct=check(start,step,end);
if(correct && (step && end)!=0){
for(var i=start; i<=end; i+=step)
document.write(i+" "); }
else document.write("Not Correct Data"); }
数字
[...Array(5).keys()];
=> [0, 1, 2, 3, 4]
字符迭代
String.fromCharCode(...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()].map(i => i + 'A'.charCodeAt(0)));
=> "ABCD"
迭代
for (const x of Array(5).keys()) {
console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
}
=> 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"
作为函数
function range(size, startAt = 0) {
return [...Array(size).keys()].map(i => i + startAt);
}
function characterRange(startChar, endChar) {
return String.fromCharCode(...range(endChar.charCodeAt(0) -
startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
类型化函数
function range(size:number, startAt:number = 0):ReadonlyArray<number> {
return [...Array(size).keys()].map(i => i + startAt);
}
function characterRange(startChar:string, endChar:string):ReadonlyArray<string> {
return String.fromCharCode(...range(endChar.charCodeAt(0) -
startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
lodash.js_.range()函数
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
=> "ABCD"
没有库的旧非es6浏览器:
Array.apply(null, Array(5)).map(function (_, i) {return i;});
=> [0, 1, 2, 3, 4]
console.log([…Array(5).keys()]);
(ES6归功于尼尔斯·彼得索恩和其他评论者)
编码为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]