如何缩小 JavaScript 中的数组?


以下是在 JavaScript 中缩小数组的代码 −

示例

 实时演示

<!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: red;
   }
   .result {
      color: blueviolet;
   }
   button {
      padding: 8px;
   }
</style>
</head>
<body>
<h1>Reduce arrays javascript</h1>
<div><pre class="sample">[1,3,5,6,9,22,15]</pre></div>
<div class="result"></div>
<button class="Btn">Sum</button>
<h3>Click on the above button to sum the elements of the array</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 3, 5, 6, 9, 22, 15];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      "Sum = " +
      arr.reduce((sum, prev) => {
         return sum + prev;
      });
   });
</script>
</body>
</html>

输出

点击“求和”按钮 −

更新于:17-7-2020

110 次浏览

开始您的职业生涯

完成课程,获得认证

开始
广告