상세 컨텐츠

본문 제목

JS 자바스크립트 문자 첫번째 위치 반환 findIndex, indexOf, search

Coding/JS

by hwlink 2021. 11. 13. 16:17

본문

Q. 문자와 문자열이 주어졌을때, getFind 함수는 주어진 문자열에서 주어진 문자가 나타나는 첫번째 위치를 반환합니다. 없으면 -1 반환

function getFind(filter, sentence) { 

    const setArr = [...sentence];
    console.log(result);
    // ['I', ' ', 'a', 'm',' ', 'a', ' ', 'h', 'a', 'c', 'k', 'e', 'r'] 
    const findIndex = setArr.findIndex(el => el === filter);
    return findIndex;
  }



const output = getFind('a', 'I am a dudud')
console.log(output) // --> 2

처음에는 인자를 배열로 변환하여 각각 검사해야하는 줄 알고 배열 메서드를 사용하려고 인자로 받을 sentence를  Spread Operator 연산자를 사용하여 result 새로운 배열에 담아 주었다. 

 

findIndex()사용

findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.

 

처음엔 findInex를 사용하여 구현하였는데 setArr, findIndex 두 개의 배열을 생성해주는게 불필요해보여 다른 2가지 풀이로 정리하려고한다.

 

 

 

다른풀이 1

String.prototype.search()

search() 메서드는 정규 표현식과  객체간에 같은 것을 찾기 위한 검색을 실행한다.

function getFind(filter, sentence) { 
    const findIndex = sentence.search(filter);
	return findIndex;
  }



const output = getFind('a', 'I am a hacker')
console.log(output) // --> 2

 

 

다른풀이 2

 

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

arr.indexOf(searchElement[, fromIndex])
function getFind(filter, sentence) { 
	const findIndex = sentence.indexOf(filter);
  	return findIndex; 
}

const output = getFind('a', 'I am a dudud')
console.log(output) // --> 2

 

관련글 더보기