Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 소프티어
- 자바스크립트
- 너비 우선 탐색
- softeer
- Lv. 0
- level 3
- Baekjoon
- Dynamic Programming
- Java
- 프로그래머스
- LEVEL 2
- Lv. 3
- javascript
- join
- Lv. 2
- 오블완
- SQL 고득점 KIT
- 동적계획법
- dfs
- 깊이 우선 탐색
- 티스토리챌린지
- SQL
- Python
- DP
- select
- Lv. 1
- programmers
- group by
- 파이썬
- bfs
Archives
- Today
- Total
몸과 마음이 건전한 SW 개발자
자바스크립트 [빈 배열을 요소로 가진 배열 만들기] 본문
코드
// 자바스크립트로 파이썬 리스트 컴프리헨션과 유사한 기능 만들기
// arr = [[] for _ in range(n)]
const n = 5; // 원하는 길이
const arr1 = Array.from({ length: n }, () => []);
const arr2 = [...Array(n)].map(() => []);
const arr3 = Array(n).fill().map(() => [])
// 예를 들어, 각 배열에 인덱스 번호를 push하고 싶다면
for (let i = 0; i < n; i++) {
arr1[i].push(i);
arr2[i].push(i);
arr3[i].push(i);
}
console.log(arr1)
console.log(arr2)
console.log(arr3)
console.time('Array.from');
const arr4 = Array.from({ length: 1000000 }, () => []);
console.timeEnd('Array.from');
console.time('Spread and map');
const arr5 = [...Array(1000000)].map(() => []);
console.timeEnd('Spread and map');
console.time('Array.fill and map');
const arr6 = Array(1000000).fill().map(() => []);
console.timeEnd('Array.fill and map');
결과
[ [ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ] ] [ [ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ] ] [ [ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ] ] Array.from: 153.349ms Spread and map: 66.776ms Array.fill and map: 59.871ms |
느낀점
- 위에 2개는 gpt가 추천해준 방법이고 아래 fill을 사용한 것은 내가 사용하는 방법인데 시간이 제일 빠르게 나오네??
'개발 언어 입문 > 자바스크립트 문법' 카테고리의 다른 글
프로그래머스 [Lv. 0] 특정 문자 제거하기 {언어 : JavaScript} (0) | 2024.08.19 |
---|---|
자바스크립트 [조건문 리펙토링] (0) | 2024.04.08 |
자바스크립트 Heap [최소힙 구현] (0) | 2024.03.25 |
자바스크립트 [배열 비교] (0) | 2024.03.17 |
자바스크립트 [sort 기본 개념] (0) | 2024.03.11 |