Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

27장 배열 #24

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open

27장 배열 #24

wants to merge 8 commits into from

Conversation

zziglet
Copy link
Member

@zziglet zziglet commented Feb 25, 2025

늦어서 죄송합니다..
메소드 예시가 꽤 많았네유..

+내용이 너무 길어서 가독성 바닥일것 같아..더 깔끔한 원본 노션 넣어놓을게유 정신병오면 참고해주셔요~ (26일 새벽)
배열 정리본 Notion 버전

zziglet and others added 4 commits February 25, 2025 19:34
27장 배열 정리본
27장 정리본 markdown 오류 수정
이미지 파일 assets으로 분리
Copy link
Member

@Turtle-Hwan Turtle-Hwan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1722 줄... 스크롤이 장난 아니네요 고생하셨습니다

Comment on lines +176 to +178
![실제 실행 시간은 이정도 차이가 발생함](./assets/image%202.png)

실제 실행 시간은 이정도 차이가 발생함
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 이건 첨 알았네요
object가 더 느리다니

console.log(arr) //[1, 2, 3, 4]
```

성능 면에서 좋지 않은 메소드 → 마지막 요소로 추가할 요소가 하나뿐일 때는 length로 직접 추가
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 이것도 첨알았네요

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

직관적인데 성능이 구리군요...

Comment on lines +593 to +595
ES6의 스프레드 문법을 사용하는 것이 더 좋은 방법(31장에서 살펴보도록 하자)

→ 함수 호출 없이 표현식으로 마지막에 요소 추가 가능, 원본 배열 수정되지 않는 장점!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

표현식으로 표기 가능해서 더 직관적인거 같아요

Comment on lines +620 to +627
`pop`과 `push`를 배웠으니 stack을 구현할 수 있다!

![image.png](./assets/image%203.png)

1. 생성자 함수로 구현하기
2. 클래스로 구현하기

~~(궁금하신 분들은 딥다이브 교재 512쪽으로..(또는 자료구조 수업으로) 내용이 많아 생략합니다.)~~
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

js에서 큐는 어떻게 구현하죠?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Queue Class를 만들어서 객체를 이용해 구현해요!


→ 제거한 요소 반환

→ 원본 배열을 직접 변경하는 메소드(mutator method)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

원본배열을 직접 변경하느냐 변경된 배열을 반환하느냐가 꽤 중요한 거 같아요


### 27.9.10 `Array.prototype.flatMap`

ES10에서 도입된 메서드로, 생성된 새로운 배열을 평탄화
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

와 이런걸 만드네요

@Turtle-Hwan Turtle-Hwan self-assigned this Feb 25, 2025
Copy link
Collaborator

@junepil junepil left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

배열 메소드가 그냥 뭉텅이로 마구마구 나와서 어지럽네요. 진짜 고생 많았어요 💯

제가 종종 사용했던 인스턴스 메소드도 추가해놨습니다.

ps : 정신병 오지 않고 다 읽는데 성공했어요

for(let i = 0; i < 10000000; i++){
arr[i] = i;
}
console.timeEnd('Array Performance Test');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

벤치마킹을 한 번도 해본적이 없는데 console.time 잘 알아 갑니다


- 값 없이 비어있는 요소를 위해 메모리 공간 확보 x, 빈 요소를 생성하지도 x

### 27.3.3 희소배열
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sparse의 의미에 '희소한'이라는 뜻이 있어서 희소 배열이라고 말하는 것 같은데 희소 배열보다는 '흩어진' 배열이 더 와닿네요

console.log(arr[0]); //1
```

존재하지 않는 요소에 접근 시 undefined가 반환된다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다른 언어들은 Index Out of Bound 오류가 뜨는데 이건 정말 위험하네요

console.log(arr) //[1, 2, 3, 4]
```

성능 면에서 좋지 않은 메소드 → 마지막 요소로 추가할 요소가 하나뿐일 때는 length로 직접 추가
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

직관적인데 성능이 구리군요...

```jsx
function sum() {
//ES5
var arr = Array.prototype.slice.call(arguments);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어지러워요 😵


**length 프로퍼티**

`map`이 생성하여 반환하는 새로운 배열의 length 프로퍼티 값 ≤ 호출한 배열의 length 프로퍼티
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`map`이 생성하여 반환하는 새로운 배열의 length 프로퍼티 값 ≤ 호출한 배열의 length 프로퍼티
`filter`이 생성하여 반환하는 새로운 배열의 length 프로퍼티 값 ≤ 호출한 배열의 length 프로퍼티


4. 중첩 배열 평탄화

⇒ 그냥 `Array.prototype.flat` 활용하자..
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤣

Copy link
Collaborator

@songeunseo songeunseo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수고하셨습니다~~~ 엄청 기네요....

Comment on lines +1138 to +1149
숫자 요소를 정렬할 때에는 정렬 순서를 정의하는 비교 함수를 인수로 전달해야 한다!

```jsx
const points = [40, 100, 1, 5, 2, 25, 10];

points.sort((a, b) => a - b);
console.log(points); // [1, 2, 5, 10, 25, 40, 100]

//숫자 배열에서의 내림차순 정렬
points.sort((a, b) => b - a);
console.log(points); // [100, 40, 25, 10, 5, 2, 10]
```
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TypedArray.prototype.sort()를 이용하면 비교함수 없이 숫자정렬이 가능합니당

const points = [40, 100, 1, 5, 2, 25, 10];
const sortedPoints = new Int32Array(points).sort();
console.log([...sortedPoints]); // [1, 2, 5, 10, 25, 40, 100]

@clicelee clicelee assigned zziglet and unassigned Turtle-Hwan Feb 27, 2025
clicelee and others added 3 commits February 27, 2025 13:06
Co-authored-by: Junepil Lee <[email protected]>
Co-authored-by: Junepil Lee <[email protected]>
Co-authored-by: Eunseo Song <[email protected]>
Copy link
Collaborator

@whddltjdwhd whddltjdwhd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

상당한 양이네요. . . 요즘 백준을 JS로 풀면서 어떤 메서드가 있는지 정확히 몰랐는데, 이번 기회에 유용한 메서드들을 많이 알 수 있었습니다! 고생하셨어요~

console.log(arr.length); //3
```

2. js에 배열이라는 타입은 존재하지 않는다. **배열은 객체 타입**이다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

만물 객체인 js...

Comment on lines +342 to +343
- `Array` 생성자 함수와 다른 점?
- 전달된 인수가 1개 and 숫자 → 그래도 인수를 요소로 갖는 배열 생성
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Array 생성자 함수
let arr1 = Array(3);
console.log(arr1);         // 출력: [ <3 empty items> ]
console.log(arr1.length);  // 출력: 3

// Array.of
let arr2 = Array.of(3);
console.log(arr2);         // 출력: [3]
console.log(arr2.length);  // 출력: 1

위와 같이 Array 생성자 함수는 인자로 들어온 숫자를 배열의 길이로 인식하고, Array.of는 숫자를 배열의 요소로 인식한다는 점에 있어 차이가 있네요!


## 27.7 배열 요소의 삭제

배열은 사실 객체 → 배열의 특정 요소를 삭제하기 위해 `delete` 연산자 사용 가능
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete 연산자는 다음과 같은 한계가 있습니다.

function Person() {
  this.name = 'Alice';
}
Person.prototype.age = 25;

const person = new Person();
delete person.name; // 직접 프로퍼티인 name은 삭제됨
delete person.age;  // person 객체에는 age가 없으므로, 프로토타입의 age는 삭제되지 않음

console.log(person.name); // 출력: undefined
console.log(person.age);  // 출력: 25 (프로토타입에서 상속받음)

객체 인스턴스의 프로퍼티만 삭제하고, 해당 객체의 프로토타입 체인 상에 있는 프로퍼티는 삭제가 불가능합니다!

그리고 객체에서 delete 연산자를 통해 프로퍼티를 삭제할 때, 객체 내부의 최적화( hidden class(또는 shape))가 해제되어 이후 속성 접근 성능에 영향을 줄 수 있습니다! (백준에서 이 문제를 겪어 봤었습니다..) 그래서 성능에 아주 민감한 경우에는 프로퍼티에 null 이나 undefined를 할당하는 방식으로 대체할 수 있습니다.

Comment on lines +505 to +506
1. 원본 배열을 직접 변경하는 메서드(**mutator method**)
2. 원본 배열을 변경하지 않고 새로운 배열을 생성하여 반환하는 메서드(**accessor method**)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어떤 메서드가 새로운 배열을 반환하는 건지... 헷갈려요ㅠㅠㅠㅠ

Comment on lines +557 to +559
- 중복 요소 여러 개가 존재 → 첫번째로 검색된 요소의 index 반환
- 두번째 인수로 검색을 시작할 index 추가 가능
- 인수로 전달된 요소가 존재하지 않음 → -1 반환
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +620 to +627
`pop`과 `push`를 배웠으니 stack을 구현할 수 있다!

![image.png](./assets/image%203.png)

1. 생성자 함수로 구현하기
2. 클래스로 구현하기

~~(궁금하신 분들은 딥다이브 교재 512쪽으로..(또는 자료구조 수업으로) 내용이 많아 생략합니다.)~~
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Queue Class를 만들어서 객체를 이용해 구현해요!

```


for문과 달리 break, continue 사용 불가 → 무조건 배열을 빠짐 없이 다 순회해야 함
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let arr = [1, 3, 5, 7, 9];

arr.forEach((num, idx) => {
  if (idx == 2) return;
  arr[idx] = num ** 2;
});

console.log(arr); // [ 1, 9, 5, 49, 81 ]

return문을 써도 마찬가지군요..!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants