- array filter map 등의 콜백 function에 추가 인자(매개 변수) 받기(add argument parameter)


//-------------------------------------
* 방법1 : 콜백함수에서 this 로 받기

function cb(element, index, array) {
    console.log(arguments, this, element, index, array);
    // arguments 로 추가 인자를 받을 수가 없음
}

['a', 'b'].filter(cb, [ 'ex1', 'ex2']); // callback 함수 뒤에 1개만 전달됨, 여러 인자 전달시 배열 사용



//-------------------------------------
* 방법2 : bind 사용

    - 주의! 인자 순서에 주의

function cb(ex1, ex2, element, index, array) {
     console.log(arguments, ex1, ex2, element, index, array);
}

['a', 'b'].filter(cb.bind(this, 'ex1', 'ex2'));



//-------------------------------------
//
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
filter(function(element, index, array) { /* ... */ }, thisArg)

https://stackoverflow.com/questions/7759237/how-do-i-pass-an-extra-parameter-to-the-callback-function-in-javascript-filter

반응형
Posted by codens