Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript의 Object.keys().map() VS Array.map()


다음은 JavaScript에서 Object.keys().map() 및 Array.map()을 보여주는 코드입니다 -

예시

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Object.keys().map() VS Array.map()</h1>
<div class="sample">{1:'A',22:'B',55:'C',19:'D'}</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to sum the keys of the above object</h3>
<div class="sample">[22,33,11,44]</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to double each element of the above array</h3>
<script>
   let resEle = document.querySelectorAll(".result");
   let BtnEle = document.querySelectorAll(".Btn");
   let obj = { 1: "A", 22: "B", 55: "C", 19: "D" };
   let arr = [22, 33, 11, 44];
   let total = 0;
   BtnEle[0].addEventListener("click", () => {
      Object.keys(obj).map((x) => (total += parseInt(x)));
      resEle[0].innerHTML = "The sum of the object keys = " + total;
   });
   BtnEle[1].addEventListener("click", () => {
      resEle[1].innerHTML = arr.map((x) => x * 2);
   });
</script>
</body>
</html>

출력

위의 코드는 다음과 같은 출력을 생성합니다 -

JavaScript의 Object.keys().map() VS Array.map()

첫 번째 '여기를 클릭' 버튼을 클릭하면 -

JavaScript의 Object.keys().map() VS Array.map()

두 번째 '여기를 클릭' 버튼을 클릭하면 -

JavaScript의 Object.keys().map() VS Array.map()