JavaScript Tutorial/Operators/typeof — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 08:24, 26 мая 2010

Get variable type

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
var x = "Hello", y;
alert("Variable x value is " + typeof(x));
alert("Variable y value is " + typeof(y));
alert("Variable z value is " + typeof(z));
//  -->
</script>
</head>
<body>
</body>
</html>


The Typeof Operator

The typeof operator takes one parameter: the variable or value to check.



var sTemp = "test string";
alert(typeof sTemp);
alert(typeof 95);


Calling typeof on a variable or value returns one of the following values:

  1. "undefined" if the variable is of the Undefined type.
  2. "boolean" if the variable is of the Boolean type.
  3. "number" if the variable is of the Number type.
  4. "string" if the variable is of the String type.
  5. "object" if the variable is of a reference type or of the Null type.

typeof

Syntax



typeof(variable)


typeof a variable: number

<html>
<head>
<title>Debug Example</title>
<script type="text/javascript">
function aFunction(iNum1) {
    if (typeof iNum1 == "number" ){
       alert("number");
    }
    if ( typeof iNum1 == "string") {
        alert("string");
    }
}
aFunction("a");
aFunction(1);
</script>
</head>
<body>
</body>
</html>


typeof a variable: string

<html>
<head>
<title>Debug Example</title>
<script type="text/javascript">
function aFunction(iNum1) {
    if (typeof iNum1 == "number" ){
       alert("number");
    }
    if ( typeof iNum1 == "string") {
        alert("string");
    }
}
aFunction("a");
aFunction(1);
</script>
</head>
<body>
</body>
</html>