JavaScript基础(一) 数据类型

动态类型

JavaScript 是一种弱类型或者说动态语言。这意味着你不用提早声明变量的类型,在程序运行过程当中,类型会被自动肯定。jquery

数据类型

最新的 ECMAScript 标准定义了 7 种数据类型:浏览器

  • 6 种 原始类型:闭包

    • Boolean函数

    • Null优化

    • Undefinedprototype

    • Numbercode

    • String对象

    • Symbol (ECMAScript 6 新定义)ip

  • 和 Object内存

typeof 检测数据类型

typeof用来检测给定变量的数据类型,返回下列某个字符串

  • "boolean” --- 变量是布尔值(true/false)

  • "undefined" --- 变量未定义

  • "string" --- 变量是字符串

  • "number" --- 变量是数值

  • "function" --- 变量是函数

  • "object" --- 变量是对象或null

  • "symbol" --- 变量是Symbol

有这样一道题目,考察 typeof 返回值类型。

typeof(typeof(new Date()))   //string

可是在实际项目中,typeof 也只是用来判断变量是undefinedfunction。由于不少类型不能精确的判断出来,例如:

Value function typeof
"foo" String string
new String("foo") String object
1.2 Number number
new Number(1.2) Number object
true Boolean boolean
new Boolean(true) Boolean object
new Date() Date object
new Error() Error object
[1,2,3] Array object
new Array(1, 2, 3) Array object
new Function("") Function function
/abc/g RegExp object
new RegExp("meow") RegExp object
{} Object object
new Object() Object object
注意
typeof /s/ ===function; // Chrome 1-12 , 不符合 ECMAScript 5.1
typeof /s/ === object; // Firefox 5+ , 符合 ECMAScript 5.1

由上得出结论,当使用检测结果是objectfunction时,咱们并不能看出实际的数据类型。

推荐使用 Object.prototype.toString(),结合call去实现对变量类型的精准判断。

Object.prototype.toString.call(null);      //”[object Null]”
Object.prototype.toString.call(undefined); //”[object Undefined]”
Object.prototype.toString.call(“abc”);     //”[object String]”
Object.prototype.toString.call(123);       //”[object Number]”
Object.prototype.toString.call(true);      //”[object Boolean]”

简单封装以下:

function _typeof(obj){
  
   if(typeof obj == object || typeof obj == function){
    var type =Object.prototype.toString.call(obj).split("")[1].toLowerCase();
    return type.match(/[a-z]/g).join("");  //正则去除字符串的]
  }
  
  return typeof obj; 
  
}

上面代码在标准浏览器中能够彻底兼容,可是IE6(虽然如今没必要兼容,也要了解下)中,却会出现如下问题:

_typeof(null);        //object
_typeof(undefined);   //object

缘由在于IE6下

Object.prototype.toString.call(undefined);  //”[object Object]”
Object.prototype.toString.call(null);       //”[object Object]”

因此要先添加判断,使用String()对象将 undefinednull转为字符串。代码以下:

function _typeof (obj){
    
    //注意到这里是 == 而不是 === ,
    //undefined 值是派生自 null 值的,因此null == undefined 返回true 
    if(obj == null){
        return String(obj)
    }
      
    if(typeof obj == "object"; || typeof obj == "function"){
      var type =Object.prototype.toString.call(obj).split(" ")[1].toLowerCase();
      return type.substring(0,type.length-1); 
    }
    
    return typeof obj; 
    
    }

String()函数遵循下列转换规则:
若是值有 toString()方法,则调用该方法(没有参数)并返回相应的结果;
若是值是 null,则返回"null";
若是值是 undefined,则返回"undefined"

这样对 typeof 的扩展就封装好了。代码还有优化空间,这里再也不继续。

Jquery已经实现了类型检测的封装,jquery.type()的内部实现以下:

//实例对象是能直接使用原型链上的方法的
var class2type = {};
var toString = class2type.toString;

jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

$.type = function( obj ) {
  //若是是null或者undefined,直接转成String返回
  //注意到这里是==而不是===,
  //undefined 值是派生自 null 值的,因此null == undefined 返回true 
  if ( obj == null ) {
    return String( obj );
  }
  //当typeof 返回 object或function, 进入core_toString 
  return typeof obj === "object" || typeof obj === "function" ?
    class2type[ core_toString.call(obj) ] || "object":
    typeof obj;
}

Undefined

Undefined 类型只有一个值,即特殊的 undefined。在使用 var 声明变量但未对其加以初始化时,这个变量的值就是 undefined,例如:

var foo;
alert(foo == undefined);  //true

undefined表示"缺乏值",就是此处应该有一个值,可是尚未定义。
典型用法是:

  1. 变量被声明了,但没有赋值时,就等于 undefined

  2. 调用函数时,应该提供的参数没有提供,该参数等于 undefined

  3. 对象没有赋值的属性,该属性的值为 undefined

  4. 函数没有返回值时,默认返回 undefined

var name;
alert(name) // undefined

function f(x){console.log(x)}
f() // undefined

var  o = new Object();
alert(o.p) // undefined

var x = f();
alert(x) // undefined

Null

Null 类型是第二个只有一个值的数据类型,这个特殊的值是 null
若是定义的变量准备在未来用于保存对象,那么最好将该变量初始化为 null

null 有时会被看成一种对象类型,可是这其实只是语言自己的一个bug,即对 null 执行 typeof null 时会返回字符串"object"

原理是这样的,不一样的对象在底层都表示为二进制,在JavaScript中二进制前三位都为0的话会被判断为object类型,null的二进制表示是全0,天然前三位也是0,因此执行 typeof 时会返回“object”。——《你不知道的JavaScript》

使用null的状况:

1.DOM,试图获取一个不存在的元素返回一个null值,而不是undefined
2.初始化一个对象的值,通常设为null
3.经过分配null值,有效地清除引用,并假设对象没有引用其余代码,指定垃圾收集,确保回收内存。

var table = document.getElementById("table"); 
console.log(table);  // null

var obj = null; //初始化对象

window.onload = function(){
    var el = document.getElementById("id");
    var id = el.id; //解除循环引用
    el.onclick = function(){
        alert(id); 
    }
    el = null; // 将闭包引用的外部函数中活动对象清除
}

Boolean

Boolean 类型是经常使用的一种类型,只有两个字面值:truefalse

注意:字面值区分大小写,True 和 False 不是 Boolean 值。

常常遇到就是其余数据类型转为boolean的问题,只要遵循一个原则:

当值为""(空字符串)、0NaNnullundefined 时,都转为false,其余状况都为true

相关文章
相关标签/搜索