배열 특정 위치(index) 찾기

Gunwoo Kim·2021년 5월 13일
0

JavaScript

목록 보기
9/17
post-thumbnail

배열 객체의 메소드

indexOf() & lastIndexOf()

1. indexOf()

: indexOf (searchElement [, fromIndex])는 배열에서 searchElement를 검색하고 첫 번째 일치 항목의 인덱스를 반환합니다.

var a = ['a', 'b', 'a', 'b', 'a'];
console.log(a.indexOf('b')); // logs 1
// Now try again, starting from after the last match
console.log(a.indexOf('b', 2)); // logs 3
console.log(a.indexOf('z')); // logs -1, because 'z' was not found

2. lastIndexOf()

: lastIndexOf(searchElement[, fromIndex])메서드는 indexOf메서드와 유사하게 작동하지만 배열의 뒤쪽에서부터 요소를 찾습니다.

var a = ['a', 'b', 'c', 'd', 'a', 'b'];
console.log(a.lastIndexOf('b')); // logs 5
// Now try again, starting from before the last match
console.log(a.lastIndexOf('b', 4)); // logs 1
console.log(a.lastIndexOf('z')); // logs -1

0개의 댓글