본문 바로가기
Frontend

[JS] $.each(), Array.forEach(), Array.some()

by unknownomad 2022. 4. 25.

$.each()

//방법
//선언된 Array의 개수만큼 반복 실행
$.each(Array, callback function(index, value) {
    //반복되는 내용   
}

//예제
const arr = ["item1", "item2", "item3"];
$.each(arr, function(index, value) {
    console.log("index= " + index + ", value= " + value);
    //return true; ➡ for문의 continue 역할
    //return false; ➡ for문의 break 역할
}

Array.forEach()

//방법
Array.forEach(callback function(value, index, array) {
    //반복 내용
});

//예제
const arr = ["item1", "item2", "item3"];
arr.forEach(function(value, index, array) {
    console.log("index= " + index);
    console.log("value= " + value);
    console.log(array);
});

Array.some()

//방법
Array.some(callback function(value, index, array) {
    //반복 내용
});

//예제
const arr = ["item1", "item2", "item3"];
arr.some(function(value, index, array) {
    console.log("index= " + index + ", value= " + value);
    console.log(array);
});

Array.forEach() vs Array.some()

1. Array.forEach()

const arr = ["item1", "item2", "item3"];
let result = arr.forEach(function(value, index, array) {
    console.log("index= " + index + ", value= " + value);
    console.log(array);
    
    if(value === "item2") {
        return true; //반복문에 영향 X
    }
});

 

2. Array.some()

const arr = ["item1", "item2", "item3"];
let result = arr.some(function(value, index, array) {
    console.log("index= " + index + ", value= " + value);
    console.log(array);
    
    if(value === "item2") {
        return true; //true: for문의 break 역할(반복문에 영향 O)
    }
});

 


출처 : https://rianshin.tistory.com/103

댓글