日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

判斷數(shù)據(jù)類型的五種方法

作者:H-hang 更新時(shí)間: 2022-09-22 編程語言

判斷數(shù)據(jù)類型的方法

1.typeof

  • 語法:
typeof operand  ||  typeof(operand)
operand可以是變量或者表達(dá)式
類型 返回值
Number number
String string
Boolean boolean
Undefined undefined
Null object
Symbol symbol
Obejct object
Array object
Function object
其他對象 object

2.instanceof

  • 語法:
object instanceof constructor
object為實(shí)例對象  constructor為構(gòu)造函數(shù)
  • js內(nèi)置構(gòu)造函數(shù):
    • Array
    • Date
    • Error
    • Function
    • Object
    • RegExp
  • 用途:
    • 用來檢查object是否為constructor的實(shí)例對象
    • 可用來判斷對象類型
    • 不可判斷原始類型
  • 示例:
var arr=[1,2,3]
console.log(arr instanceof Array) //true

var arr=[1,2,3]
console.log(arr instanceof Object) //true

var reg=/^\d{3,}$/
console.log(reg instanceof RegExp)  //true

function Person(){};
var student = new Person();
console.log(peason1 instanceof Person)  //true

3.Array.isArray()

  • 語法:
Array.isArray()
  • 用途:
    • 用于檢測某變量是否為數(shù)組,返回值是Boolean型
  • 示例:
var arr = [1,2,3]
Array.isArray(arr)  //true

4.Object.prototype.toString.call()

  • 語法:
Object.prototype.toString.call()
括號(hào)內(nèi)輸入需要判斷的內(nèi)容

同時(shí)可以使用slice方法截取返回值
Object.prototype.toString.call().slice(8,-1)
  • 用途:

    • 用于判斷瀏覽器內(nèi)置對象
    • 可判斷所有數(shù)據(jù)類型
    • 返回值是字符串
  • 示例:

Object.prototype.toString.call(1).slice(8,-1)  //'Number'

Object.prototype.toString.call('').slice(8,-1)  //'String'

Object.prototype.toString.call(true).slice(8,-1)  //'Boolean'

Object.prototype.toString.call(undefined).slice(8,-1)  //'Undefined'

Object.prototype.toString.call(null).slice(8,-1)  //'Null'

Object.prototype.toString.call([]).slice(8,-1)  //'Array'

Object.prototype.toString.call({}).slice(8,-1)  //'Object'

Object.prototype.toString.call(function(){}).slice(8,-1)  //'Function'

Object.prototype.toString.call(new Date).slice(8,-1)  //'Date'

5.constructor

  • 語法:
object.constructor
  • 用途:
    • constructor屬性返回對象的構(gòu)造函數(shù)
    • 且返回值是函數(shù)的引用
    • 不是函數(shù)名
  • 示例:
[].constructor === Array  //true

Number(1).constructor === Number //true

''.constructor === String //true

new Date().constructor === Date //true

new Error().constructor === Error //true

true.constructor === Boolean  //true

  • 注意:
    • null和undefined沒有constructor,這兩種類型的數(shù)據(jù)需要通過其他方式判斷
    • 同時(shí)函數(shù)的constructor是不穩(wěn)定的,這個(gè)主要體現(xiàn)在自定義對象上,當(dāng)開發(fā)者重寫protype后,原有的constructor引用會(huì)丟失,constructor會(huì)默認(rèn)為Object

原文鏈接:https://blog.csdn.net/SH744/article/details/126824792

欄目分類
最近更新