當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS 判断变量类型(判断数据类型、typeof)
生活随笔
收集整理的這篇文章主要介紹了
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] } 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?
總結
以上是生活随笔為你收集整理的JS 判断变量类型(判断数据类型、typeof)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Aspose.Words提示The do
- 下一篇: Linux学习总结(三)之 putty,