数据类型
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>阿西吧</title>
</head>
<body>
<p> typeof 操作符返回变量、对象、函数、表达式的类型。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof NaN + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34} + "<br>" +
typeof new Date() + "<br>" +
typeof function () {} + "<br>" +
typeof myCar + "<br>" +
typeof null;
</script>
</body>
</html>
运行结果
typeof 操作符返回变量、对象、函数、表达式的类型。
string
number
number
boolean
object
object
object
function
undefined
object
判断数据类型
constructor 属性
constructor 属性返回所有 JavaScript 变量的构造函数。
实例
"John".constructor // 返回函数 String() { [native code] }
(3.14).constructor // 返回函数 Number() { [native code] }
false.constructor // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor // 返回函数 Array() { [native code] }
{name:'John', age:34}.constructor // 返回函数 Object() { [native code] }
new Date().constructor // 返回函数 Date() { [native code] }
function () {}.constructor // 返回函数 Function(){ [native code] }
判断数组
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>啊洗吧</title>
</head>
<body>
<p>判断是否为数组。</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>
</body>
</html>
运行结果
判断是否为数组。
true
判断日期
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>啊洗吧</title>
</head>
<body>
<p>判断是否为日期。</p>
<p id="demo"></p>
<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>
</body>
</html>
运行结果
判断是否为日期。
true
undefined
在 JavaScript 中, undefined 是一个没有设置值的变量。
typeof 一个没有值的变量会返回 undefined。
实例
var person; // 值为 undefined(空), 类型是undefined
null
在 JavaScript 中 null 表示 "什么都没有"。
null是一个只有一个值的特殊类型。表示一个空对象引用。
你可以设置为 null 来清空对象:
实例
var person = null; // 值为 null(空), 但类型为对象
undefined 和 null 的区别
实例
null 和 undefined 的值相等,但类型不等:
typeof undefined // undefined
typeof null // object
null === undefined // false
null == undefined // true