[js] Array 한줄로 초기화 (initialize) 하기

2021. 7. 17. 17:45Frontend/JS

** 초보 개발자로 글에 수정해야 할 부분이 있을 수 있습니다. 정정해야 할 부분은 댓글로 소통 부탁드립니다!

 

안녕하세요! 

코딩하다보면 그럴 때 있지 않나요 ~ 

한 줄로 코드를 끝내는 능력자이고 싶다! ㅋㅋㅋ(하지만 현실은... 벌써 몇 백줄 넘어가는 중... 🥲)

하지만 조금씩 스킬을 늘려나가다 보면 그런 날도 오겠죠?! 

 

서론은 여기까지하고

이번에는 한 줄로 Array 초기화 하는 방법을 알아보려 합니다.

 


 

보통 배열 초기화는 아래와 같은 코드로 수행합니다.

var data = [];
var length = 5; // user defined length

for(var i = 0; i < length; i++) {
    data.push(createSomeObject());
}

 

이런 코드를 한 줄로 끝낼 수는 없을까? 고민하던 중 구글링을 통해 해결할 수 있었습니다!

 

1. 

Array.from(arrayLike[, mapFn[, thisArg]])
  • arrayLike : 배열로 변환하고자 하는 유사 배열 객체반복 가능한 객체(string, array, iterable object 등)
  • mapFn : 배열의 모든 요소에 대해 호출할 맵핑 함수
  • thisArg : mapFn 실행 시에 this로 사용할 값

 

Array.from('abcde') // gives ['a', 'b', 'c', 'd', 'e']
Array.from('x'.repeat(5)) // gives ['x', 'x', 'x', 'x', 'x']
Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]

 

 

2. 

func.apply(thisArg, [argsArray])
  • thisArg : function을 호출할 때 제공될 this 인자
  • argsArray : function의 인자(유사배열 객체 또는 null, undefined)

 

Array.apply(null, Array(5)).map(function (x, i) { return i; }) 
// gives [0, 1, 2, 3, 4]

 

 

[References]

 

Array.from() - JavaScript | MDN

Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듭니다.

developer.mozilla.org

 

 

Function.prototype.apply() - JavaScript | MDN

apply() 메서드는 주어진 this 값과 배열 (또는 유사 배열 객체) 로 제공되는 arguments 로 함수를 호출합니다.

developer.mozilla.org

 

 

How to initialize an array's length in JavaScript?

Most of the tutorials that I've read on arrays in JavaScript (including w3schools and devguru) suggest that you can initialize an array with a certain length by passing an integer to the Array

stackoverflow.com

 

'Frontend > JS' 카테고리의 다른 글

[js] Event Delegation(이벤트 위임)  (0) 2021.07.06
[js] window.location 객체  (0) 2021.06.30
[js] event 전파 멈추기  (0) 2021.06.24
[js] object to array 변환  (0) 2021.06.23
[js] javascript 깔끔한 코드를 위한 꿀팁 10  (0) 2021.06.22