js数据类型

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

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

    typeof的使用:

    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"
原文地址:https://www.cnblogs.com/wxcbg/p/6119697.html