array.map(callbackFunction(currenValue, index, array), thisArg)
< array.map 예시 >
const numbers = [ 1,2,3,4,5];
const newNumbers = numbers.map(number =>number *2);
console.log(newNumbers);
//[2, 4, 6, 8, 10]
map() 함수는 기존의 배열을 callbackFunction에 의해 새 배열을 만드는 함수이다.
하지만 원본의 배열이 변하지는 않는다.
map 함수는 Object(객체)타입도 컨트롤 할 수 있다.
const students = [
{name: 'Jun', age: 28},
{name: 'seho', age: 25},
{name: 'dong', age: 28},
{name: 'gwon', age: 27},
];
const names = students.map(student => student.name);
//['Jun', 'seho', 'dong', 'gwon']
const ages = students.map(age => student.age);
//[28, 25, 28, 27]
초기값부터 시작하여 증가 or 감소하면서 조건에 부합되면 계속 순회해준다. 중간에 'break'을 만나면 반복문을 중단해준다.
for(초기식; 조건식; 증감식) {
조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 실행문;
}
array.forEach(callback(currentvalue[, index[, array]])[, thisArg])
array.map(callback(currentValue[, index[, array]])[, thisArg])
// array 요소가 추가되는 경우
const numbers = [1, 2, 3, 4, 5];
const result = numbers.map(number => {
numbers.push(number);
return number * number;
});
console.log(result);
// [1, 4, 9, 16, 25];
// array 요소가 수정되는 경우
const numbers = [1, 2, 3, 4, 5];
const result = numbers.map(number => {
numbers.pop();
return number * number;
});
console.log(result);
// [1, 4, 9, empty × 2];
오늘은 오랜만에 개발자로 일하고 있는 친구를 만나서 모각코를 하게 되었다. 원래 오늘은 localStorage에 대하여 더 공부를 하려 했는데 친구와 얘기중 얕은복사, 깊은복사 이야기가 나오고 이야기를 하다보니 콜백함수, map함수 등의 얘기가 나와서 map함수에 대해 공부를 하게 되었다. 아직은 콜백함수에 대하여 100% 이해가 되지는 않지만 대략의 흐름을 파악하게 되었고 원본을 건드리지않는다는 점에서 slice()와 헷갈리기도 하였지만 원본을 복사한다는 점과 원본을 가져와서 다른작업을 한 다음 리턴할 수 있다는 점에서 차이점을 알게 되었다. (좋은 질문이라고 하였다!) 처음 공부하였을 때와 달리 개념과 전개방식을 이해하면서 공부하게되니 더욱더 이해도 잘되고 재밌는 것 같다. 조만간 얕은복사, 깊은복사에 대해서도 다시 한 번 학습해야겠다.