美文网首页
JavaScript中的数据类型

JavaScript中的数据类型

作者: 婷楼沐熙 | 来源:发表于2017-03-08 09:52 被阅读20次

一、JavaScript中的数据类型

JS中的数据类型分为以下七类:

  • 6 种原始类型:
  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol (ECMAScript 6 新定义)
  • 和 Object(复杂类型)
    Object又分为:
  • Function
  • Array
  • Date
  • RegExp

二、typeof操作符

typeof true; // 'boolean';
typeof null; // object
typeof undefined; // undefined
typeof 1; // number
typeof ''; // string
typeof Symbol(); // 'symbol';
typeof []; // object
typeof {}; // object

三、如何区分数组和对象

从上面的结果可知typeof无法区分数组和对象。总结一些下面的方法来区分它们。

  • typeof加length属性
    数组有length属性,object没有。
let arrayDeal = ['red', 'green'];
let objectDeal = {'blue', 'yellow'};
function getType (test) {
    if(typeof o == 'object'){
        if( typeof o.length == 'number' ){
            return 'Array'; 
        }else{
            return 'Object';    
        }
    }else{
        return 'param is no object type';
    }
}
  • instanceof
({})  instanceof Object; // true
([])  instanceof Array; // true

但数组也是属于object,因此我们要利用instanceof判断数据类型是对象还是数组时应该优先判断array,最后判断object。

  • isArray
    Array.isArray() 该方法适用于确定传递的值是否为Array。
Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
  • Object.prototype.toString.call()
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [o

因为返回值是字符串所以可以用.slice(8, -1)方法去掉[object]

var getType = function (elem) {
  return Object.prototype.toString.call(elem).slice(8, -1);
},

相关文章

网友评论

      本文标题:JavaScript中的数据类型

      本文链接:https://www.haomeiwen.com/subject/dctbgttx.html