js empty array

new Array(n)으로 초기화한 배열에 array api가 동작하지 않았다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const arr = new Array(5);

console.log(arr.length, arr); // 5 [ <5 empty items> ]
console.log(arr.push(1), arr); // 6 [ <5 empty items>, 1 ]
console.log(arr.push(2), arr); // 7 [ <5 empty items>, 1, 2 ]

console.log(arr.map((v) => v * 2)); // [ <5 empty items>, 2, 4 ]

arr.forEach((v) => {
console.log(v);
});
// 1
// 2

console.log(`-----------`);

for (let index = 0; index < arr.length; index++) {
const element = arr[index];
console.log(element);
arr[index] = undefined;
}
// undefined
// undefined
// undefined
// undefined
// undefined
// 1
// 2

console.log(`-----------`);

arr.forEach((v) => {
console.log(v);
});
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined
  • 위에 map이나 forEach를 보면 array api가 초기화하지 않은 인덱스에 대해 동작하지 않는 것을 확인할 수 있다
  • 직접 for문으로 찍어보면 undefined이라 나온다
  • 그러면서 undefined으로 전부 초기화해줬다
  • 직접 초기화해주니까 array api forEach가 동작하는 것을 확인할 수 있다
  • array api를 동작하지 않는 것을 경험했다
1
const arr = new Array(5).fill(0);
  • 이런 식으로 특정 값으로 직접 초기화를 해줘야 스킵되지 않고 정상적으로 api를 사용할 수 있다
Author

chinsung

Posted on

2021-07-01

Updated on

2021-07-12

Licensed under

댓글