Array.prototype.map()
map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
arr.map(callback(currentValue[, index[, array]])[, thisArg])
forEach랑 비슷한 함수이지만 반환값을 이용해서 다른(새로운) 배열을 만들 수 있다는점
const texts = ['a', 'b', 'c']
const caps = texts.map(function(x) {
return x.toUpperCase();}
)
caps = ['A' , 'B' , 'C']
*원래 배열인 texts 자체를 바꾸진 않음. 그렇기에 다른 변수를 설정해줘야됨
array안에 object가 있는 경우에도 사용 가능 - 당연한거임
const fullNames = [{first: 'Albus', last: 'Dumbledore'}, {first: 'Harry', last: 'Potter'}, {first: 'Hermione', last: 'Granger'}, {first: 'Ron', last: 'Weasley'}, {first: 'Rubeus', last: 'Hagrid'}, {first: 'Minerva', last: 'McGonagall'}, {first: 'Severus', last: 'Snape'}];
// Write your code here
const firstNames = fullNames.map(function (x) {return x.first})
*꼭 다른 변수 설정 / return 써주기!!
'JS' 카테고리의 다른 글
JS setTimeout / setInterval (0) | 2022.09.21 |
---|---|
Arrow Function (0) | 2022.09.21 |
JS forEach (0) | 2022.09.20 |
복습) JS this (0) | 2022.09.20 |
8 - local storage에 저장하기 (0) | 2022.09.18 |