자바스크립트
자바스크립트 map함수
안양사람
2020. 6. 25. 13:56
728x90
SMALL
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
아마 이 함수를 사용하기 전에는 for문으로 해결했을 겁니다. map은 장점이 있지만 경우에 따라 for문을 사용해야 하는 경우도 있습니다.
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
간단한 map 예제입니다. array1의 각각의 요소에 접근해서 *2를 하고 그 배열을 return해줍니다.
var kvArray = [{key:1, value:10},
{key:2, value:20},
{key:3, value: 30}];
var reformattedArray = kvArray.map(function(obj){
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
// reformattedArray는 [{1:10}, {2:20}, {3:30}]
이와 같이 배열 속 객체를 재구성 할수도 있습니다.
if (this.props.match.params.pageId === undefined) {
lists = this.props.postList.map((list, index) => (
<tr key={index}>
<td className="title">
<Link to={`/community/${this.props.match.params.category}/page/1/${list.id}`}>
{list.title} [{list.comment}]
</Link>
</td>
<td className="user_displayName">
<Link to="/">{list.user_displayName}</Link>
</td>
<td className="time">{list.modified}</td>
<td className="view">{list.view}</td>
</tr>
));
}
map의 두번째 인자에 index를 넣을수도 있고 이런식으로 react에서 사용할 수도 있습니다.
728x90
LIST