zoukankan      html  css  js  c++  java
  • js基本数据类型和typeof

    JavaScript数据类型是非常简洁的,它只定义了6中基本数据类型

    • null:空、无。表示不存在,当为对象的属性赋值为null,表示删除该属性
    • undefined:未定义。当声明变量却没有赋值时会显示该值。可以为变量赋值为undefined
    • number:数值。最原始的数据类型,表达式计算的载体
    • string:字符串。最抽象的数据类型,信息传播的载体
    • boolean:布尔值。最机械的数据类型,逻辑运算的载体
    • object:对象。面向对象的基础
    复制代码
    #当弹出一个变量时:
    
    var aa;alert(aa);  //变量定义,弹出undefined
    
    alert(aa);        //变量未定义,undefined , 未定义的变量也是undefined
    
    
    #当判断一个变量是否存在时:
    
    var str;if( str == undefined )    //变量定义,可以这样判断
    
    if( str == undefined )     //变量未定义,报错ReferenceError: str is not defined
    
    所以,当判断一个变量是否不存在时,用 if( typeof str == undefined )
    复制代码

    typeof:

    复制代码
    alert(typeof 1);                // 返回字符串"number"  
    alert(typeof "1");              // 返回字符串"string"  
    alert(typeof true);             // 返回字符串"boolean"  
    alert(typeof {});               // 返回字符串"object"  
    alert(typeof []);               // 返回字符串"object "  
    alert(typeof function(){});     // 返回字符串"function"  
    alert(typeof null);             // 返回字符串"object"  
    alert(typeof undefined);        // 返回字符串"undefined"
    复制代码
    console.log({}.constructor === Object) //true
    console.log([].constructor === Array) //true
    console.log(null.constructor === null) //报错Cannot read property 'constructor' of null,可以看出来null没有constructor属性
    console.log(12.12.constructor === Number) //true
    console.log(function(){}.constructor === Function) //true
    console.log(undefined.constructor === Nudefined) //报错Cannot read property 'constructor' of null,可以看出来undefined没有constructor属性

    所以从上面的可以看出来:数组,对象,null三个typeof返回的都是object,所以我们可以使用constructor来辨别它们,数组.constructor = Array;对象.constructor = Object;而null没有constructor属性.

    JavaScript解释器认为null是属于object数据类型的一种特殊形式,而function(){}是function类型,也就是说函数也是一种基本数据类型,而不是对象的一种特殊形式。

    实际上,在JavaScript中,函数是一个极容易引起误解或引发歧义的数据类型,它可以是独立的函数类型,又可以作为对象的方法,也可以被称为类或构造器,还可以作为函数对象而存在等。

  • 相关阅读:
    最常被程序员们谎称读过的计算机书籍
    天气城市代码,市级城市. 用java的map.中国天气网.
    你所知道的学习方法,都是错的!
    解决「问题」,不要解决问题
    [IOS 下重温设计模式] AbstractFactory
    判断UIView是否装载完成
    va_start、va_end、va_list的使用
    [IOS 下重温设计模式] Singleton
    IOS BLOCK收集
    SEL
  • 原文地址:https://www.cnblogs.com/fireporsche/p/6542946.html
Copyright © 2011-2022 走看看