작심 365

array.map() 본문

Front-End/javascript

array.map()

eunKyung KIM 2021. 8. 22. 00:16

 

배열의 map() 

 

map함수는 정의된 함수를 배열(array)의 모든 item에 적용시켜준다.

그리고는 변경된 배열을 리턴해준다.

 

아래 예제에서는  colorList라는 배열에 6가지의 색을 저장하고 그 배열의 모든 아이템을

map() 함수를 이용해서 변경해 리턴해주었다.

적용한 함수는 모든 배열의 기존값 뒤에 ✨이모티콘을 추가해주는것이다.

 

let colorList = ["red","orange","yellow","green","blue","purple"];

let newColorList = colorList.map(function(color){
	
    return color + " ✨"

	});
  
  
console.log(colorList);
 // 결과
 ["red","orange","yellow","green","blue","purple"]
 
console.log(newColorList);

// 결과
 ["red ✨", "orange ✨", "yellow ✨", "green ✨", "blue ✨", "purple ✨"]

 

또다른 예제는 배열의 각 아이템의 길이를 반환해주는 배열을 리턴해준다.

 

let newList = ["abc","abcd","a"].map(function(item){
	return item.length;
    });
 
console.log(newList);

// 결과
[ 3, 4 ,1 ]

 

 

 

 

 

 

 

 

Comments