String형 배열 seoul의 element중 Kim의 위치 x를 찾아, 김서방은 x에 있다는 String을 반환하는 함수, solution을 완성하세요. seoul에 Kim은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다.
배열 내의 요소의 최초의 인덱스를 리턴하는 indexOf()
메소드를 이용하여 풀어야겠다고 생각했다.
💻 M Y C O D E 💻
function solution(seoul) { return `김서방은 ${seoul.indexOf("Kim")}에 있다`; }
화살표 함수를 통해 한 줄로 나타낼 수 있다는 점..!
const solution = (arr) => `김서방은 ${arr.findIndex(s => s === 'Kim')}에 있다`;
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
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()
메서드는 대소문자를 구분한다.