JavaScript 中数组的展开运算符

javascriptweb developmentobject oriented programming更新于 2025/8/29 23:08:17

展开 (…) 语法允许我们在需要 0+ 个参数的地方展开可迭代数组。它允许我们将多个参数作为数组传递给函数。

以下是在 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: 20px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
}
</style>
</head>
<body>
<h1>Spread operator for arrays JavaScript</h1>
<div class="sample">[22,55,11,19,55]</div>
<div class="result"></div>
<br />
<button class="btn">点击此处</button>
<h3>Click on the above button to call the add function and pass the above
array as parameter</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   function add(num1, num2, num3, num4, num5) {
      return num1 + num2 + num3 + num4 + num5;
   }
   let arr = [22, 55, 11, 19, 55];
   BtnEle.addEventListener("click", (event) => {
      resEle.innerHTML = "The sum of the above array = " + add(...arr);
   });
</script>
</body>
</html>

输出

点击‘点击此处’按钮 −


相关文章


有用资源