다시, 자바스크립트 (5) - 문자열 메서드 + 구조분해할당 + 루프 + 배열 메서드

Junho Yun·2023년 3월 17일
0
post-thumbnail

문자열 메서드

자바스크립트에서는 문자열에 사용할 수 있는 많은 메서드가 있고, 이는 코딩테스트에서 아주 잘 활용될 수 있으니 잘 알아두자

자바스크립트에서 메서드(method)는 객체(object)가 가지고 있는 함수(function)를 의미합니다. 객체는 속성(property)과 메서드로 구성되며, 속성은 객체의 상태를 나타내고, 메서드는 객체의 동작을 정의합니다.

즉, 메서드는 함수다! 그렇기 때문에 어떤 값을 파라미터로 넣어주면, 어떤 값이 반환되는 지를 잘 알아야 한다.

기본기

  • indexOf(): 문자열에서 지정된 값이 처음 나타나는 위치를 반환한다.

  • slice(): 문자열의 지정된 부분을 새 문자열로 반환한다.

  • toUpperCase / toLowerCase(): 문자열 내의 모든 문자를 대문자/소문자로 바꾼다

// indexOf() 메서드 예시
const str = 'hello world';
console.log(str.indexOf('world')); // 출력 결과: 6

// slice() 메서드 예시
const str2 = 'hello world';
const slicedStr = str2.slice(0, 5);
console.log(slicedStr); // 출력 결과: hello

// toUpperCase() 메서드 예시
const str3 = 'hello world';
const upperCaseStr = str3.toUpperCase();
console.log(upperCaseStr); // 출력 결과: HELLO WORLD

// toLowerCase() 메서드 예시
const str4 = 'HELLO WORLD';
const lowerCaseStr = str4.toLowerCase();
console.log(lowerCaseStr); // 출력 결과: hello world

ES6 추가 메서드

  • startsWith(): 매개변수로 받은 값으로 문자열이 시작하는 지 확인한다. (대소문자 구분함)

  • endsWith(): 매개변수로 받은 값으로 문자열이 끝나는 지 확인한다. (대소문자 구분함)

  • includes(): 매개변수로 받은 값이 문자열에 포함되는 지 확인한다.

  • repeat(): 인수로 받은 만큼 반복한다.

위의 3가지 메서드의 경우에는 boolean 값을 반환하고, repeat은 반복한 결과 문자열을 반환 합니다.

// startsWith() 메서드 예시
const str = 'hello world';
console.log(str.startsWith('hello')); // 출력 결과: true

// endsWith() 메서드 예시
const str2 = 'hello world';
console.log(str2.endsWith('world')); // 출력 결과: true

// includes() 메서드 예시
const str3 = 'hello world';
console.log(str3.includes('world')); // 출력 결과: true

// repeat() 메서드 예시
const str4 = 'hello';
console.log(str4.repeat(3)); // 출력 결과: hellohellohello

구조분해할당 (destructuring)

구조분해할당 문법은 배열의 값 또는 객체의 속성을 풀어서 별개의 변수로 쓸 수 있게 해주는 자바스크립트 표현식 입니다.

객체 구조분해할당

옛날에는 하나씩 지정을 해줬다면, ES6 이후에는 구조분해할당으로 간결하고 가독성 좋게 작성할 수 있다. 이는 아래 예시 뿐만 아니라 서버통신에서도 많이 사용하니 꼭 적응해놓자.

const user = {
  name: 'John Doe',
  age: 30,
  address: {
    city: 'Seoul',
    country: 'South Korea'
  }
};
// 옛날 버전
var oldName = person.name;
var oldAge = person.age;

// 객체의 속성을 변수로 분해하여 할당하기
const { name, age } = user;
console.log(name); // 출력 결과: John Doe
console.log(age); // 출력 결과: 30

// 중첩된 객체의 속성도 변수로 분해하여 할당하기
const { address: { city, country } } = user;
console.log(city); // 출력 결과: Seoul
console.log(country); // 출력 결과: South Korea

// 기본값(default value) 설정하기
const { nickname = 'unknown' } = user;
console.log(nickname); // 출력 결과: unknown

// 객체의 속성 이름을 변경하여 변수로 할당하기
const { name: fullName, age: userAge } = user;
console.log(fullName); // 출력 결과: John Doe
console.log(userAge); // 출력 결과: 30
console.log(name); // 문법 에러 발생 (객체의 속성 부여한 코드만 봤을 떄 기준) 

배열 구조분해할당

배열도 사실 객체라서 다를 것은 없다 다만 {} 대신에 []가 들어간다는 것만 생각해보면 되겠다.
또한 객체에서는 key값이 있다면, 배열에서는 index가 있기 때문에 이 점을 주의하자

const [a, b, c] = arr;
기본적인 원리는 위의 코드에서 a는 arr[0], b는 arr[1] 이런식으로 할당을 받습니다.
a,b,c는 내가 원하는 변수명을 지정하면 됩니다.

// 배열 생성
const arr = [1, 2, 3];

// 구조 분해 할당을 사용하여 각 요소를 개별 변수로 분해
const [a, b, c] = arr;

// 변수를 출력
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

// 배열 생성
const arr2 = ['apple', 'banana', 'orange'];

// 구조 분해 할당을 사용하여 첫 번째 요소와 나머지 요소를 분해
const [first, ...rest] = arr2;

// 변수 출력
console.log(first); // 'apple'
console.log(rest); // ['banana', 'orange']

활용해서 변수 교체하기

구조분해할당 사용하면 두개의 값 (혹은 여러개)을 쉽게 교체할 수 있습니다.

// 변수 생성
let a = 1;
let b = 2;

// 디스트럭처링을 이용하여 변수 값을 교체
[a, b] = [b, a];

// 변수 출력
console.log(a); // 2
console.log(b); // 1

루프

for문만 알고 있다면 아쉽다. ES6에서는 for of 가 추가되었고, 겸사겸사 for in도 알아보자

  • for of : 반복문은 iterable 객체(배열, 문자열, 맵(Map), 셋(Set), DOM 컬렉션 등)에서 요소를 반복(iterate)하면서 반복 작업을 수행합니다.

  • for in : 객체(object)의 속성(property)을 열거(enumerate)하면서 반복 작업을 수행합니다
    (반복 중에 추가 수정 삭제 하지 말 것.)

  • 차이점 : for in은 배열의 키 목록을 반환하는 반면, for of는 배열의 원소 목록을 반환한다.

// 배열 생성
const arr = ['apple', 'banana', 'orange'];

// for...of 반복문을 사용하여 배열 순회
for (const item of arr) {
  console.log(item);
}

// 객체 생성
const obj = { a: 1, b: 2, c: 3 };

// for...of 반복문을 사용하여 객체 순회
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}

위의 코드는 for of를 사용해서 배열과 객체의 루프를 진행한 코드입니다.

const person = {
  name: "Alice",
  age: 30,
  occupation: "Software Engineer"
};

for (const property in person) {
  console.log(`${property}: ${person[property]}`);
}

위의 코드는 for in을 사용해서 배열과 객체의 루프를 진행한 코드입니다.

배열 메서드

  • Array.from() : 유사 배열 객체나 이터러블 객체를 배열로 변환합니다.

  • Array.of() : 전달받은 인수들로 새로운 배열을 생성합니다.

  • Array.find() : 주어진 콜백 함수가 참인 첫 번째 요소를 반환합니다. 없을 경우 undefined를 반환합니다.

  • Array.findIndex() : 주어진 콜백 함수가 참인 첫 번째 요소의 인덱스를 반환합니다. 없을 경우 -1을 반환합니다

  • Array.some(), Array.every() : 배열 요소 중 하나라도 / 모든 요소가 주어진 콜백 함수가 참을 반환하면 true를 반환합니다. 그렇지 않으면 false를 반환합니다.

const str = "hello";
const arr = Array.from(str); // ["h", "e", "l", "l", "o"]

const arr1 = Array.of(1, 2, 3); // [1, 2, 3]
const arr2 = Array.of(5); // [5]

const numbers = [1, 2, 3, 4, 5];

const evenNumber = numbers.find(num => num % 2 === 0); // 2
const evenNumberIndex = numbers.findIndex(num => num % 2 === 0); // 1
const hasEvenNumber = numbers.some(num => num % 2 === 0); // true
const isEven = numbers.every(num => num % 2 === 0); // false
profile
의미 없는 코드는 없다.

0개의 댓글