728x90

1~N 만큼의 배열을 선언후 사용할일이 있을 경우, [1 2, 3, 4, 5 … N] 만큼의 값을 선언 후 사용하는 방법도 있으나, 자바스크립트에서 제공하는 Array.from 과 map 내장함수를 이용하여 함수화 하여 선언 후 사용이 가능합니다.

예제

// 1 ~ 10  까지의 배열 선언이 필요한 경우

// 방법 (1)
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// 방법 (2)
const arr2 = Array.from({length: 10}).map((v, k) => k + 1);
// > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// 방법 (3)
const arr3 = Array.from({length: 10}, (v, k) => k + 1);
// > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

또한 특정 문자열에 대해 각각의 문자를 기준으로 배열 변환이 필요한 경우에도 마찬가지로 Array.from 을 이용하여 변환이 가능합니다

예제 - 문자열 배열 변환

const arr = Array.from('Hello world');
// > ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
const arr2 = Array.from('12345678910');
// > ['1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0']

시퀀스 함수를 구현해 놓는다면 재사용성 높게 활용이 가능합니다.

const range = n => Array.from({length:n}, (v, k) => k);
console.log(range(10));

// > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.from 은 length 속성과 인덱싱 요소를 가진 객체(유사배열객체) 나 반복 가능한 객체에 대해 배열로의 반환이 가능함으로, Set, Map에서의 배열 변환도 가능합니다.

예제 - Set 배열 변환

const arr = new Set(['hello world', window]);
Array.from(arr);
// > ['hello world', Window]

예제 - Map 배열 변환

const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// > [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// > ['a', 'b'];

Array.from(mapper.keys());
// > ['1', '2'];

Array.from 은 Array.from(arrayLike[, mapFn[, thisArg]]) 이와같이 mapFn 을 선택 매개변수로 가지고 있으며 필요에 따라 배열의 각 요소를 맵핑할때 사용이 가능합니다.

그렇기 때문에 처음 1~N 까지의 배열을 만들때 방법 (3)과 같이 선언하여 사용하는 방법도 가능하게 됩니다.

Array.from 은 ES6 에 추가된 문법으로써, 어떠한 표준 구현체에서는 사용할 수 없을 수 있습니다.

다른 모든 코드 이전 최상단에 아래 코드를 넣으면 지원하지 않는 플랫폼에서도 Array.from 기능을 사용할 수 있습니다.

코드

// Production steps of ECMA-262, Edition 6, 22.1.2.1
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;
    };
  }());
}
728x90

+ Recent posts