PHP에서는 다음을 수행할 수 있습니다.
range(1, 3); // Array(1, 2, 3) range("A", "C"); // Array("A", "B", "C")
즉, 상한과 하한을 넘으면 숫자나 문자의 범위를 얻을 수 있는 기능이 있습니다.
이를 위해 JavaScript에 기본 제공이 있습니까?그렇지 않은 경우 어떻게 구현해야 합니까?
질문에 대한 답변
숫자
[...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.lodash 함수
_.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()]);
(Nilspetersohn 및 기타 논객에 대한 ES6 크레딧)
번호에는 ES6를 사용할 수 있습니다.Array.from()
현재는 IE를 제외한 모든 것으로 동작하고 있습니다.
단축판:
Array.from({length: 20}, (x, i) => i);
긴 버전:
Array.from(new Array(20), (x, i) => i);
0 ~ 19 의 배열을 작성합니다.이것은, 다음의 몇개의 형식으로 단축할 수 있습니다.
Array.from(Array(20).keys()); // or [...Array(20).keys()];
하한과 상한을 지정할 수도 있습니다. 예를 들어 다음과 같습니다.
Array.from(new Array(20), (x, i) => i + *lowerBound*);
상세한 것에 대하여는, http://www.2ality.com/2014/05/es6-array-methods.html 를 참조해 주세요.
새로운 마음에 드는 폼 (ES2015)
Array(10).fill(1).map((x, y) => x + y)
또, 다음의 기능을 필요로 하는 경우는,step
파라미터:
const range = (start, stop, step = 1) =>
Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
MDN 문서에서 제안할 수 있는 다른 구현은 다음과 같습니다.
// Sequence generator function
// (commonly referred to as "range", e.g. Clojure, PHP etc) const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step))
여기 2센트 있습니다.
function range(start, end) {
return Array.apply(0, Array(end - 1))
.map((element, index) => index + start); }
이것은 문자와 숫자에 대해 동작하며, 옵션의 순서로 앞뒤로 이동합니다.
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
.
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;
}
console.log(range("A", "Z", 1)); console.log(range("Z", "A", 1)); console.log(range("A", "Z", 3));
console.log(range(0, 25, 1));
console.log(range(0, 25, 5)); console.log(range(20, 5, 5));