arr.map(callback, [thisArg])
새로운 배열을 return 하기 때문에 변수 생성 후 사용 -> 불변성 유지
map 안에 함수를 이용하여 원하는 규칙 return
function(num)의 num은 numbers의 첫번째 index부터 마지막 index까지 순회한다.
var numbers = [1,2,3,4,5];
var processed = numbers.map((num)=>{
return num*num
})
// processed = [1,4,9,16,25]
const IterationSample = () => {
const names = ['눈사람', '얼음', '눈' ,'바람'];
const nameList = names.map((name)=>{
return <li>{name}</li>
})
retrun <ul>{nameList}</ul>
}
const nameList = names.map((name, index)=>{
return <li key={index}>{name}</li>
})
index를 사용하지 않고 key를 만든다.
const IterationSample = () => {
const [names, setNames] = useState([
{id:1, text:'눈사람'},
{id:2, text:'얼음'},
{id:3, text:'눈'},
{id:4, text:'바람'},
])
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(5); // 새로운 항목에 추가할 id
const nameList = names.map(name => {
return <li key = {name.id}>{name.text}</li>
})
return <ul>{nameList}</ul>
}
이벤트 추가
concat으로 불변성 유지 ( push로 직접적으로 추가 금지 )
const onChange = (e) => {
setInputText(e.target.value);
};
const onClick = () => {
const nextNames = names.concat({
id: nextId,
text: inputText,
});
setNextId(nextId + 1);
setNames(nextNames);
setInputText('');
};
/*
const nextNames = {
id: nextId,
text: inputText,
};
setNextId(nextId + 1);
setNames([...nextNames, names]); // spread 연산자 사용
setInputText('');
};
*/
return (
<div>
<input
value={inputText}
message="inputText"
placeholder="값 입력"
onChange={onChange}
/>
<button onClick={onClick}>추가</button>
<ul>{nameList}</ul>;
</div>
);
특정 조건을 만족하는 원소들을 분류
분류된 배열 새로운 배열로 return -> 불변성 유지
filter()
const numbers = [1,2,3,4,5,6];
const biggerThanThree = numbers.filter(number => number > 3);
// biggerThanThree = [4,5,6]
구현
const onRemove = (id) => {
const nextName = names.filter((name) => name.id !== id);
setNames(nextName);
};
const nameList = names.map((name) => {
return (
<li key={name.id} onDoubleClick={() => onRemove(name.id)}>
{name.text}
</li>
);
});