Computer >> Máy Tính >  >> Lập trình >> Javascript

Tham số hàm JavaScript

Truyền các tham số khác nhau trong khi gọi một hàm. Các tham số được truyền này có thể được nắm bắt bên trong hàm và bất kỳ thao tác nào có thể được thực hiện trên các tham số đó. Một hàm có thể nhận nhiều tham số được phân tách bằng dấu phẩy.

Sau đây là mã để triển khai các tham số hàm trong JavaScript -

Ví dụ

<!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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Function Parameters</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above buttons to see the function parameters </h3>
<script>
   let sampleEle = document.querySelector(".sample");
   test(param1, param2, param3, param4) {
      sampleEle.innerHTML = "The parameters for the function are <br>";
      Array.from(arguments).forEach((element, index) => {
         sampleEle.innerHTML += "Parameter " + index + " = " + element + "<br>";
      });
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      test("Hello", "world", 22, 99);
   });
</script>
</body>
</html>

Đầu ra

Tham số hàm JavaScript

Khi nhấp vào nút “BẤM VÀO ĐÂY” -

Tham số hàm JavaScript