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 {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Passing primitive/object types to function</h1>
<div class="result"></div>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the above button to pass primitive and object to a function and call it</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let person = { name: "Rohan", age: 12, city: "Delhi" };
   function printObj(obj) {
      resEle.innerHTML = "Name = " + obj.name + "<br>";
      resEle.innerHTML += "age = " + obj.age + "<br>";
      resEle.innerHTML += "city = " + obj.city + "<br>";
   }
   function printPrimitive(prim) {
      resEle.innerHTML += prim;
   }
   BtnEle.addEventListener("click", () => {
      printObj(person);
      printPrimitive(22);
   });
</script>
</body>
</html>

输出

单击“单击此处”按钮后 −


更新于: 2020 年 7 月 16 日

191 次浏览

开启你的 职业

完成课程获得认证

开始吧
广告