알고리즘 문제풀기 06. 서울에서 김서방 찾기

주히 🌼·2020년 12월 24일
0

JavaScript_Algorithm

목록 보기
6/7

문제 설명

String형 배열 seoul의 element중 Kim의 위치 x를 찾아, 김서방은 x에 있다는 String을 반환하는 함수, solution을 완성하세요. seoul에 Kim은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다.

제한사항

  • seoul은 길이 1 이상, 1000 이하인 배열입니다.
  • seoul의 원소는 길이 1 이상, 20 이하인 문자열입니다.
  • "Kim"은 반드시 seoul 안에 포함되어 있습니다.

입출력 예

어떻게 풀었는가? 🤷‍♀️

배열 내의 요소의 최초의 인덱스를 리턴하는 indexOf() 메소드를 이용하여 풀어야겠다고 생각했다.

💻 M Y C O D E 💻

function solution(seoul) {
    return `김서방은 ${seoul.indexOf("Kim")}에 있다`;
}

참고하고 싶은 코드 💻

화살표 함수를 통해 한 줄로 나타낼 수 있다는 점..!

const solution = (arr) => `김서방은 ${arr.findIndex(s => s === 'Kim')}에 있다`;

기록하고 싶은 부분 📃

① indexOf()

indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

🧨 string에서 사용하는 indexOf() 메서드

indexOf() 메서드는 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다. 일치하는 값이 없으면 -1을 반환한다.

var anyString = 'Brave new world';

console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
// 첫번째 w 문자 위치는 8
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// 마지막 w 문자 위치는 10

console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
// 첫번째 new 문자열 위치는 6
console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
// 마지막 new 문자열 위치는 6

참고로 indexOf() 메서드는 대소문자를 구분한다.

profile
하면 된다! 프론트앤드 공부 중 입니당 🙆‍♀️

0개의 댓글