TIL 27 day 빈배열과 For...of, For...in

Winney·2020년 10월 2일
0

1. 빈배열

1) 빈배열 만들기

(1) const firstArr = new Array();
(2) const secondArr = Array();
(3) const thirdArr = [];

2) 빈배열 내 요소 개수 지정하기

(1) const firstArrEle = new Array(8)
console.log(firstArrEle); // [empty × 8] or [ <8 empty items> ]
즉, [ , , , , , , , ] 이런 모습으로 8개의 요소가 빈상태로 빈 배열을 만들 수 있다.
(2) const secondArrEle = Array(8);
위와 같은 결과이다.

3) 빈배열 채우기

(1) const forthArrFill = new Array(4).fill('item')
console.log(forthArrFill); // [ 'item', 'item', 'item', 'item' ]
(2) const fifthArrFill = Array(4).fill('item')
console.log(fifthArrFill); // [ 'item', 'item', 'item', 'item' ]

2. For문

예시

  1. 배열의 prototype으로 foo라는 함수를 추가함
Array.prototype.foo = function() {
  return 100;
}
  1. 배열 colors 선언
const colors = ['red', 'green', 'blue']

1) For...of

for(const color of colors) {
    console.log(color);
}

결과

'red'
'green'
'blue'

For...of
(1) 반복 할 수 있는 것들만 반복한다.
(2) 순서를 나열 할 수 있는 것들만 반복한다.
(3) prototype chain에 영향을 받지 않는다.

2) For...in

for(const color in colors) {
  console.log(color);
}

결과

'0'
'1'
'2'
'foo'
for(const color in colors) {
  console.log(color, colors[color]);
}

결과

'0' 'red'
'1' 'green'
'2' 'blue'
'foo' [Function]

for...in
(1) 반복할 수 없는 것도 반복한다.
(2) 반복 시 index가 담겨있다.
(3) prototype chain에 영향을 받는다.

profile
프론트엔드 엔지니어

0개의 댓글