判断变量的类型

1.  typeof

对于基本类型,除了null类型其他类型都能判断正确。

JS 中分为七种内置类型,七种内置类型又分为两大类型:基本类型和对象(Object)(引用类型)。

 基本类型有六种: nullundefinedbooleannumberstringsymbol

基本类型是指非 对象 并且方法的数据

1   var up="he is a super man";
2   var output=up.charAt(5);
3   console.log(output);//a

 

 

当执行 第二行代码时后台会 var up=new String("he is a super man");

找到对应的包装对象,包装成一个和up值相等的对象返 回
  var output=up.charAt(5);

调用方法返回给output,
  up=null; 然后销毁

2.Object.prototype.toString

JavaScript里使用typeof判断数据类型,只能区分基本类型,即:numberstringundefinedbooleanobject
对于nullarrayfunctionobject来说,使用typeof都会统一返回object字符串。
要想区分对象、数组、函数、单纯使用typeof是不行的。在JS中,可以通过Object.prototype.toString方法,判断某个对象之属于哪种内置类型。
1 var up="he is a super man";  
2 var x = Object.prototype.toString.call(up);
3 console.log(x);      //[object String]

 

 

posted @ 2019-03-31 13:04  访书  阅读(409)  评论(0编辑  收藏  举报