JavaScript 中的 Object.keys().map() 與 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>輸出
以上的程式碼將會輸出如下內容 −

單擊第一個“單擊此處”按鈕 −

單擊第二個“單擊此處”按鈕 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP