안규 공부방

Javascript & JQuery & CSS > jQuery 배열 inArray() - 배열검색 예제

등록일 : 2017-07-04 19:38 조회수 : 94,981

1. inArray() 개요 : 배열 내의 값을 찾아서 인덱스를 반환합니다.(요소가 없을 경우 -1을 반환).
 
	jQuery.inArray( value, array [, fromIndex] )
	value 찾을 value.
	array 대상 배열
	fromIndex 검색이 시작될 배열의 인덱스. 기본값은 0이고 배열 전체를 검색합니다.



$.inArray() 함수는 JavaScript의 기본 함수인 .indexOf() 함수와 유사합니다. 만일 배열 내에 첫번째 요소가 value 인자와 일치한다면 $.inArray() 함수는 0을 리턴합니다.
예제
		<!DOCTYPE html>
		<html>
		<head>
		  <style>
		  div { color:blue; }
		  span { color:red; }
		</style>
		  <script src="http://code.jquery.com/jquery-latest.js"></script>
		</head>
		<body>
		  
		<div>"John" found at <span></span></div>
		<div>4 found at <span></span></div>
		<div>"Karl" not found, so <span></span></div>
		<div>"Pete" is in the array, but not at or after index 2, so <span></span></div>
		<script>var arr = [ 4, "Pete", 8, "John" ];
		var $spans = $("span");
		$spans.eq(0).text(jQuery.inArray("John", arr));
		$spans.eq(1).text(jQuery.inArray(4, arr));
		$spans.eq(2).text(jQuery.inArray("Karl", arr));
		$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
		</script>

		</body>
		</html>



아래는 결과값입니다.
 
"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1
	
아래와 같은 형태로 배열을 검색하게 됩니다.

	jQuery.inArray("John", arr)
	jQuery.inArray(4, arr)
	jQuery.inArray("Pete", arr, 2)

	맨 마지막 인자 2에 주목하세요. 인덱스 기준 2보다 큰 배열 요소부터 검색하는 것입니다.

	indexOf() 같이 사용하는 거니까 그리 어려운 개념은 아니네요. jQuery 구문 중에 배열 요소를 찾을 때 사용해 보아요~
※ 혹시 도움이 되셨다면 댓글에 한마디 남겨주세요!
작성자   비밀번호
자동글 방지     (자동글 방지 기능입니다.)
내용   댓글달기 
이메일 문의 : cak0280@nate.com  
Copyright 2000 By ENTERSOFT.KR All Rights Reserved.