如何在 JavaScript 函式中使用 typeof 引數?


Arguments 物件是傳遞給函式的引數。它是一個所有函式都可訪問的變數。假設向函式傳遞了兩個引數,那麼你可以像下面這樣訪問它們

arguments[0]
arguments[1]

以相同的方式,你可以在 JavaScript 中使用 typeof 引數。首先,讓我們看看如何使用 typeof。typeof 運算子是一個單目運算子,它放在其單個運算元之前,該運算元可以是任何型別。 

示例

以下程式碼演示瞭如何實現 typeof 運算子

即時演示

<html>
   <body>
      <script>
         var a = 20;
         var b = "String";
         var linebreak = "<br />";

         result = (typeof b == "string" ? "B is String" : "B is Numeric");
         document.write("Result => ");
         document.write(result);
         document.write(linebreak);

         result = (typeof a == "string" ? "A is String" : "A is Numeric");
         document.write("Result => ");
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>

現在讓我們看看如何在 JavaScript 中使用 typeof 引數。typeof 引數會返回一個類似這樣的物件

document.write(typeof arguments);

假設你有兩個引數,那麼使用 typeof,你可以像下面這樣引用它們,它將返回 typeof 引數。

document.write(typeof arguments[0]);
document.write(typeof arguments[1]);

更新於:2020-01-09

720 次瀏覽

開始你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.