현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.
This is a new technology, part of the ECMAScript 2015 (ES6) standard .
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.
요약
Array.from() 메소드는 유사 배열 혹은 반복가능한 객체로부터 새 Array 인스턴스를 만듭니다.
ES6에서 클래스 구문은 내장 클래스 및 사용자 정의 클래스의 서브 클래스화를 허용합니다. 결과적으로, Array.from과 같은 클래스 정적 메소드는 Array가 아닌, Array의 서브 클래스를 상속받고 서브 클래스의 새 인스턴스를 만듭니다.
구문
Array.from(arrayLike[, mapFn[, thisArg]])
매개 변수
arrayLike- 배열로 변환할 유사 배열 혹은 반복 가능한 객체.
mapFn- 선택 사항. 배열 모든 요소에 호출 할 Map 함수.
thisArg- 선택 사항.
mapFn실행 시에this로 사용할 값.
설명
Array.from()은 다음으로부터 Array를 만듭니다:
Array.from()는 선택 매개변수인 mapFn를 가지는데, 이 매개변수는 배열(혹은 서브 클래스 객체)의 각 요소에 대해 map 함수를 실행합니다. 좀 더 정확하게, 중간에 배열을 만들지 않는 점을 제외한다면, Array.from(obj, mapFn, thisArg)는 Array.from(obj).map(mapFn, thisArg)와 같습니다. 이 특징은 typed arrays와 같은 특정 배열 서브 클래스에서 중간 배열 값이 적절한 유형에 맞게 생략되기 때문에 특히 중요합니다.
from() 메소드의 length 속성은 1입니다.
예시
// Array-like object (arguments) to Array
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [1, 2, 3]
// Any iterable object...
// Set
var s = new Set(["foo", window]);
Array.from(s);
// ["foo", window]
// Map
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]
// String
Array.from("foo");
// ["f", "o", "o"]
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]
// Generate a sequence of numbers
Array.from({length: 5}, (v, k) => k);
// [0, 1, 2, 3, 4]
폴리필(Polyfill)
Array.from은 ECMA-262 6차 표준에서 추가되었기에, 다른 표준의 구현 사항에서는 존재하지 않을 수 있습니다. 다음 코드를 스크립트의 시작 부분에 추가함으로써, Array.from이 기본적으로 지원되지 않는 환경에서도 해당 메소드를 사용할 수 있습니다. ECMA-262 6차 버전에 지정되어 있는 이 알고리즘은 Object와 TypeError가 각자 원래 값을 가지게 하고, callback.call이 Function.prototype.call의 원래 값을 구하도록 합니다. 또한, 실제 iterable이 폴리필 될 수 없기에, 이 구현 방법에서는 ECMA-262 6차 버전에 정의되어 있는 제네릭 iterable을 지원하지 않습니다.
// Production steps of ECMA-262, Edition 6, 22.1.2.1
// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
if (!Array.from) {
Array.from = (function () {
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function (value) {
var number = Number(value);
if (isNaN(number)) { return 0; }
if (number === 0 || !isFinite(number)) { return number; }
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function (value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike/*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError("Array.from requires an array-like object - not null or undefined");
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
명세
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.from' in that specification. |
Standard | Initial definition. |
브라우저 호환성
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | Not supported | 32 (32) | Not supported | Not supported | Not supported |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | Not supported | Not supported | 32.0 (32) | Not supported | Not supported | Not supported |