Write a function findNeedle() that takes an array full of junk but containing one "needle" After your function finds the needle it should return a message (as a string) that says:"found the needle at position " plus the index it found the needle, so:
Example(Input --> Output) ["hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"] --> "found the needle at position 5" Note: In COBOL, it should return "found the needle at position 6"
문제 풀이
function findNeedle(haystack) {
let needlePosition = haystack.indexOf("needle");
return `found the needle at position ${needlePosition}`
}
배열 내에서 일치하는 문자열의 위치를 반환하는 indexOf 메소드를 이용해서 needle의 위치를 변수로 선언
이후 백틱 문자를 사용해서 문자열을 작성하고 needle 문자열의 위치는 needlePosition 변수를 불러오는 것으로 코드 작성
코드 비교
function findNeedle(array) {
for (var i=0; i<array.length; i++){
if (array[i] === 'needle')
return 'found the needle at position ' + i;
}
for 구문의 조건 부분에 만약 array의 배열이 needle과 같으면 'found the needle at position ' + i;이라는 문자열을 반환하는 코드로 작성했다.