String형 배열 seoul의 element중 Kim의 위치 x를 찾아, 김서방은 x에 있다는 String을 반환하는 함수, solution을 완성하세요. seoul에 Kim은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다.
- seoul은 길이 1 이상, 1000 이하인 배열입니다.
- seoul의 원소는 길이 1 이상, 20 이하인 문자열입니다.
- Kim은 반드시 seoul 안에 포함되어 있습니다.
seoul 배열 안에있는 값들중 Kim이 있다면 그 값의 인덱스를 반환함
function solution(seoul) { for (let i=0; i<seoul.length; i++) { if(seoul[i] == "Kim") { return `김서방은 ${i}에 있다` } } }
function solution(seoul) { const indexKim = seoul.indexOf("Kim"); return `김서방은 ${indexKim}에 있다` }
: findIndex 메소드는 배열안에 제공된 함수의 조건을 만족하는 첫번째 인덱스를 반환한다. 만족되는 요소가 없으면 -1을 반환한다.
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test
function solution(seoul) { const indexKim = seoul.findIndex(x => x == "Kim"); return `김서방은 ${indexKim}에 있다` }
cf) array.prototype.find() : the find() method, which returns the value of an array element, instead of its index.