100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > JS 判断变量类型(判断数据类型 typeof)

JS 判断变量类型(判断数据类型 typeof)

时间:2022-06-11 22:47:40

相关推荐

JS 判断变量类型(判断数据类型 typeof)

数据类型

<!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] }newDate().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

实例

varperson;// 值为 undefined(空), 类型是undefined

null

在 JavaScript 中 null 表示 "什么都没有"。

null是一个只有一个值的特殊类型。表示一个空对象引用。

你可以设置为 null 来清空对象:

实例

varperson =null;// 值为 null(空), 但类型为对象

undefined 和 null 的区别

实例

null 和 undefined 的值相等,但类型不等:

typeofundefined// undefinedtypeofnull// objectnull=== undefined// falsenull== undefined// true

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。