HTML&CSS&Javscript&Jquery
190819 reduce,map 예제
猫猫
2019. 8. 23. 17:29
반응형
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
var test3d = [
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]
];
//세로 더하기
result =
test3d.reduce(function(a,b){ //a에 차례대로 b를 더할건데.
//reduce 처음 실행 시 a= [1,2,3] b=[4,5,6]
return(
a.map(function(i,index){ //a.map으로 i,index만큼 회전할것.
//[1,2,3].map(i,index)
//i = 1 index 0
console.log(i); //여기서 찍어보면 1,2,3,5,7,9,12,15,18 이 찍힘
i+=b[index];
//i+=b[0~] = i+b[0] = 1+4
console.log("i: ",i, "b[index]: ", b[index]);
//5,7,9,12,15,18,22,26,30 이 출력됨
//첫번쨰 :1+4, 2+5, 3+6,
//두번째: 5+7, 7+8, 9+9
//세번째:12+10, 15+11, 18+12
return i; //결국 마지막 리턴값은 //22,26,30으로 리턴하는것
})
)
});
console.log(result);
</script>
</head>
<body>
</body>
</html>
반응형