자바 스크립트 each index - jaba seukeulibteu each index

$(selector).each(function(index,element))

- 일반적인 방식

*return false를 사용하여 반복을 중지시킬 수 있다.

$.each( array, callback )

- 유틸리티 방식

- $.each() 함수는 단독 객체를 반복하는 $(selector).each() 와 다르다.

- 이 방식은 객체든 배열이든 모두 사용 가능하다.


참조

api.jquery.com/jquery.each/

www.w3schools.com/jquery/misc_each.asp

자바 스크립트 each index - jaba seukeulibteu each index

JavaScript의 forEach 메서드는 배열을 순회하는 여러 방법 중 하나입니다. 사용자는 실행하는 작업에 따라 각각의 특징을 고려하여 어떤 메서드를 사용할지 결정해야 합니다.

이 기사에서는 JavaScript의 forEach 메서드를 자세히 살펴보겠습니다.

다음과 같은 숫자 배열이 있습니다.

const numbers = [1, 2, 3, 4, 5];

기존의 for 반복문을 사용해 배열을 순회하는 방법은 다음과 같습니다.

for (i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
} 

forEach 메서드도 배열을 순회하기 위해 사용되지만, 기본적인 for 반복문과는 다른 방식으로 함수를 사용합니다.

forEach 메서드는 다음 매개변수(parameter)와 함께 배열의 각 요소에 적용하게 될 콜백 함수(callback function)를 전달합니다.

  • Current Value (명명된 매개변수) - 처리할 현재 요소
  • Index (선택적 매개변수) - 처리할 현재 요소의 인덱스
  • Array (선택적 매개변수) - forEach 메서드를 호출한 배열

주어진 매개변수를 하나씩 설명하겠습니다.

우선 forEach 메서드를 사용해 배열을 순회하려면 콜백 함수 또는 익명 함수가 필요합니다.

numbers.forEach(function() {
    // code
});

콜백 함수는 각 요소에 대해 실행되며, 배열의 요소를 나타내는 매개변수를 반드시 하나 이상 사용해야 합니다.

numbers.forEach(function(number) {
    console.log(number);
});

그럼 배열을 순회해볼까요?

자바 스크립트 each index - jaba seukeulibteu each index

ES6 화살표 함수 표현을 사용하면 코드를 단순화할 수 있습니다.

화살표 함수 표현 예시:

numbers.forEach(number => console.log(number));

선택적 매개변수

인덱스(Index)

이어서 선택적 매개변수에 대해 알아봅시다.

첫 번째 선택적 매개변수는 각 요소의 순서를 나타내는 인덱스입니다.

즉 두 개의 매개변수를 활용하여 메서드를 사용하면 두 번째 매개변수를 통해 요소의 인덱스를 확인할 수 있습니다.

numbers.forEach((number, index) => {
    console.log('Index: ' + index + ' Value: ' + number);
});

자바 스크립트 each index - jaba seukeulibteu each index

배열(Array)

배열 매개변수는 필요에 따라 다양하게 활용할 수 있는 선택적 매개변수로, 원본 배열 그 자체입니다. 단순히 호출하기만 하면 배열의 요소 수만큼 배열이 출력되는 것을 볼 수 있습니다.

numbers.forEach((number, index, array) => {
    console.log(array);
});

자바 스크립트 each index - jaba seukeulibteu each index

다음 영상에서는 forEach 메서드의 활용 사례를 볼 수 있습니다 (주석: 원문 글쓴이의 영상이기 때문에 내용은 영어로 되어있습니다).

브라우저 지원

Array.forEach 메서드는 IE 버전 8 이하를 제외한 모든 브라우저에서 지원됩니다.

자바 스크립트 each index - jaba seukeulibteu each index
caniuse.com

제 유튜브 채널에서 웹 개발에 대해 더 자세한 내용을 확인해보세요.

읽어주셔서 감사합니다.



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

jQuery.each( array, callback )Returns: Object

Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • version added: 1.0jQuery.each( array, callback )

    • array

      The array or array-like object to iterate over.

    • callback

      The function that will be executed on every value.

  • version added: 1.0jQuery.each( object, callback )

    • object

      The object to iterate over.

    • callback

      The function that will be executed on every value.

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

1

2

3

$.each([ 52, 97 ], function( index, value ) {

alert( index + ": " + value );

This produces two messages:

0: 52
1: 97

If an object is used as the collection, the callback is passed a key-value pair each time:

1

2

3

4

5

6

7

"flammable": "inflammable",

$.each( obj, function( key, value ) {

alert( key + ": " + value );

Once again, this produces two messages:

flammable: inflammable
duh: no duh

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Examples:

Iterates through the array displaying each number as both a word and numeral

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

<title>jQuery.each demo</title>

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

var arr = [ "one", "two", "three", "four", "five" ];

var obj = { one: 1, two: 2, three: 3, four: 4, five: 5 };

jQuery.each( arr, function( i, val ) {

$( "#" + val ).text( "Mine is " + val + "." );

// Will stop running after "three"

return ( val !== "three" );

jQuery.each( obj, function( i, val ) {

$( "#" + i ).append( document.createTextNode( " - " + val ) );

Demo:

Iterates over items in an array, accessing both the current item and its index.

1

2

3

$.each( [ "a", "b", "c" ], function( i, l ){

alert( "Index #" + i + ": " + l );

Iterates over the properties in an object, accessing both the current item and its key.

1

2

3

$.each({ name: "John", lang: "JS" }, function( k, v ) {

alert( "Key: " + k + ", Value: " + v );