728x90

each 메소드와 map 메소드의 차이점을 알아보자.


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var intArray = new Array(1, 2, 3, 4, 5);
$.each(intArray, function(index, element) {
  if (element === 3) {
    return false;
  }
  console.log(element);
});

$.map(intArray, function(element, index) {
  if (element === 3) {
    return false;
  }
  console.log(element);
});
</script>
</head>
<body>
</body>
</html>


위 예제를  실행해보면 결과에 차이가 난다.

$.map([], callback(elementOfArray, indexInArray))
$.each([], callback(indexInArray,
element))


callback function 의 index, element(item) 위치가 서로 반대다.

each 메소드는 index 가 먼저고, 그 다음에 element 가 온다.


each 메소드

- jQuery 객체/배열의 수 만큼 반복하고, 선택된 요소들에 함수를 실행한다.

- 배열과 length 속성을 갖는 배열과 비슷한 객체들을 index를 기준으로 반복할 수 있다.

- jQuery 유틸리티 메소드 : .each(object, function(index, element) ) { 실행 함수 }

- jQuery 일반 메소드 : $(selector).each(function(index, item){ 실행함수 })

- jQuery 객체들을 위한 반복 로직을 처리하기 이해 만들어졌다.

- each 메소드에서 this 는 current element 를 가리킨다.


each 메소드는 원래의 배열을 반환(returns the original array) 하지만,

map 메소드는 제공된 배열 데이터를 변환시켜 다시 새로운 배열 객체를 반환(returns a new array)한다.

map 메소드를 과다 사용하면 많은 메모리를 낭비할 수 있다.


$(selector).each(...) 는 selector 아이템으로 반복 처리한다.
$.map() 메소드는 selector 를 사용하지 않는다.


실행결과는

each 메소드는 조건이 false를 만나면 loop 를 break 하여 결과는 1, 2 만 나온다.

map 메소드는 조건만 skip 하여 결과는 1, 2, 4, 5 가 나온다.

블로그 이미지

Link2Me

,