728x90

Definition and Usage
map() creates a new array from calling a function for every array element.
map() calls a function once for each element in an array.
map() does not execute the function for empty elements.
map() does not change the original array.

map을 이용하면 원 배열을 변경하지 않고 새로운 배열을 만든다.

map은 forEach와 마찬가지로 Array 각 요소를 순회하며 callback 함수를 실행한다. callback에서 return 되는 값을 배열로 반환한다.

 

const arr = [123];
const new_arr = new Array(123);
 
console.log('arr',arr);
console.log('new_arr',new_arr);
console.log(typeof arr === "object");
console.log(Object.values(arr));
 
// Array map() 함수를 이용하여 배열의 요소들을 변경하여 새로운 배열로 리턴
const arr1 = [12345];
 
const result1 = arr1.map(x => x + 1);
console.log('result1', result1);
 
const result_map = arr1.map(x => x * x);
console.log('result_map',result_map);
 
const result_old = [];
for (i = 0; i < arr1.length; i++) {
   result_old.push(arr1[i] * arr1[i]);
}
console.log('result_old',result_old);
 
const result3 = arr1.map(function (x,index){
   console.log(`arr1[${index}] = ${x}`);
   return x*3;
});
console.log('result3',result3);
 
 
const users = [
   { name'지민', age: 22 },
   { name'철수', age: 32 },
   { name'재석', age: 21 },
   { name'종민', age: 35 },
];
 
// 특정 요소만 재정의
const newUsers = users.map(user => {
   if (user.name === '철수') {
      return { ...user, age: 38 };
   }
   return { ...user };
});
console.log(newUsers);
// keys() is not supported in Internet Explorer 11 (or earlier).
console.log(Object.keys(newUsers));
console.log(Object.values(newUsers));
// The entries() method is not supported in Internet Explorer 11 (or earlier).
console.log(Object.entries(newUsers));
for (const [key, value] of Object.entries(newUsers)) {
   console.log(key, value);
}
 
/***
 * 자바스크립트엔 여덟 가지 자료형(숫자형, bigint형, 문자형, 불린형, 객체형, Null형, Undefined형, 심볼형)이 있다.
 * const 키워드에 객체를 할당하면 당연히 객체를 가리키는 주소 값이 할당된다. 그리고 이 주소 값은 불변이다.
 * 객체는 참조값을 통해 관리되고 있어 객체의 속성 값이 재할당 되더라도 오류가 발생되지 않는다.
 */
users[0].age = 18// const 키워드로 선언된 객체의 속성값은 재할당할 수 있다.
console.log(users);

 

 

 

블로그 이미지

Link2Me

,