js数据类型转换-数据类型判断

17次阅读

共计 5990 个字符,预计需要花费 15 分钟才能阅读完成。

数据类型

js 的数据类型有七种,其中有六种基本类型:null,undefined,boolean,string,number,symbol;以及一种引用类型:object

数据类型的转换

显式转换

一. 将非数值转换为数值类型的函数:Number(); parseInt(), parseFloat()
Number() 函数转换规则:

  • boolean:true 转换为 1,false 转换为 0
  • number:原样输出
  • undefined:输出 NaN
  • null:输出 0
  • 字符串:
    字符串中只包含数字(可带正负号,可为整数或小数):转为十进制数,且忽略前导 0;
    字符串为十六进制,转为十进制;
    空字符串:0;
    其他:NaN
  • 对象:根据不同的对象用继承的 valueOf()转成字符串, 数字或本身,而对象用 toString 就一定转为字符串。一般对象默认调用 valueOf()。
0 == []; // true, 0 == [].toString(); ---> 0 == 0;
'0' == []; // false, '0' == [].toString(); ---> '0' == '';
2 == ['2']; // true, 2 == ['2'].valueOf(); ---> 2 == '2' ---> 2 == 2;
'2' == [2]; // true, '2' == [2].toString(); ---> '2' =='2';
 
[] == ![]; //true, [].valueOf() == !Boolean([]) -> 0 == false ---> 0 == 0;

parseInt(string [,radix])

parseInt 不遵循四舍五入,radix 的取值可为 2 -32
对于非字符串类型,先转换为字符串 
从左向右遍历字符串,直到碰到非数字字符进行“截断”;如果第一个字符就是非数字字符,转换为 NaN
var num = ["123" , "124.4" , "234asd" , "asf456"] ;
  for (i = 0; i < num.length; i++) {console.log(parseInt(num[i]));   
  }     //123,124,234,NaN 

二. 将其它类型的数据转换为字符串类型的函数
2.1 String(mix):将 mix 转换成字符串类型。该函数可以将任何数据类型的值转换为字符串。
2.2 toString():

    num.toString([radix]):可以将数值(或其他除 null,undefined 外的数据类型)转换为字符类型,radix 可选;例:把一个二进制的数 10001000 转换成十六进制的数。
var num1 = parseInt('10001000',2);  //136
var num2 = num1.toString(16);  //'88'

三. 将值转换成布尔值类型:Boolean()
只有这七个值会返回 false:undefined, null, -0, +0, NaN, ”(空字符), false; 其他情况都会返回 true

Boolean(1) ;// 返回 true
Boolean("0");// 返回 true
Boolean("abc");// 返回 true
Boolean([]); // true
Boolean({}); // true
Boolean(new Boolean(false))// true
Boolean(false);// 返回 false
Boolean('');// 返回 false
Boolean(0);// 返回 false

隐式转换

这里说的隐性类型转换,是 == 引起的转换。

如果存在 NaN,一律返回 false
再看有没有布尔,有布尔就将布尔转换为数字
接着看有没有字符串, 有三种情况,对方是对象,对象使用 toString 进行转换;对方是数字,字符串转数字;对方是字符串,直接比较;其他返回 false
如果是数字,对方是对象,对象取 valueOf 进行比较, 其他一律返回 false
null, undefined 不会进行类型转换, 但它们俩相等
这个顺序一定要死记,这是面试时经常问到的。

0 == undefined    //false
1 == true        //true
2 == {valueOf: function(){return 2}}        //true
NaN == NaN    //false
 8 == undefined    //false
1 == undefined    //false
 null == {toString: function(){return 2}}        //false
 0 == null        //false
 null == 1        //false
 1 == {toString:function(){return 1} , valueOf:function(){ return [] }}         //true

//undefined 不发生类型转换
 console.log(undefined == undefined);  //true
 console.log(undefined == 0);       //false
 console.log(undefined > 0);        //false
 console.log(undefined < 0);        //false
 
//null 不发生类型转换
 console.log(null == null);        //true
 console.log(null >= 0);          //true
 console.log(null == 0);          //false
 console.log(null > 0);          //false
 console.log(null < 0);          //false
 console.log(undefined == null);    //true 

隐式转换为字符

  • +””(空字符串)
     var a;
        var b = a + "";
        console.log(typeof b + " " + b);
 
        a = null;
        b = a + "";
        console.log(typeof b + " " + b);
 
        a = 123;
        b = a + "";
        console.log(typeof b + " " + b);
 
        a = true;
        b = a + "";
        console.log(typeof b + " " + b);

        null+"3"        //"null3"

隐式转换为数值

+‘3’//     3‘10’-20  // -10
10-‘one’//   NaN

隐式转换为 boolean

!!num 相当于调用 Boolean(num)

关于 null == 0

要比较相等性之前,不能将 null 和 undefined 转换成其他任何值。就是 undefined 和 null 与其他数在进行相等判断时不进行类型转换。
null == undefined, 这个是 true

null>0 //null 转化为 number,为 0,所以 0 >0 结果为 false。
null>=0 //null 转化为 number,为 0 >=0,所以结果为 true。
null==0// null 在做相等判断时,不进行转型,所以 null 和 0 为不同类型数据,结果为 false

关于 NaN

NaN 属于 number 类型,NaN 与任何值都不相等
方法 parseInt() 和 parseFloat() 在不能解析指定的字符串时就返回这个值。

typeof(NaN)        //number
NaN === NaN   //false

注意 Number.isNaN()和 isNaN 的区别:

console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(Math.sqrt(-2))); // true
console.log(Number.isNaN('hello')); // false
console.log(Number.isNaN(['x'])); // false
console.log(Number.isNaN({})); // false


console.log(isNaN('hello')); // true
console.log(isNaN(['x'])); // true
console.log(isNaN({})); // true

数据类型判断的四种方法

  1. typeof
    typeof 的返回值有 6 种:“number”、”string”、”boolean”、”object”、”function”、”undefined”
    typeof 对于基本数据类型判断是没有问题的,但是遇到引用数据类型(如:Array)是不起作用的,返回 object
typeof [] ; //object
  1. instanceof

instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true, 否则返回 false。在这里需要特别注意的是:instanceof 检测的是原型,我们用一段伪代码来模拟其内部执行过程:

instanceof (A,B) = {
    var L = A.__proto__;
    var R = B.prototype;
    if(L === R) {
        // A 的内部属性 __proto__ 指向 B 的原型对象
        return true;
    }
    return false;
}

从上述过程可以看出,当 A 的 proto 指向 B 的 prototype 时,就认为 A 就是 B 的实例,我们再来看几个例子

[] instanceof Array; // true
{} instanceof Object;// true
new Date() instanceof Date;// true
 
function Person(){};
new Person() instanceof Person;
 
[] instanceof Object; // true
new Date() instanceof Object;// true
new Person instanceof Object;// true

instanceof 只能用来判断两个对象是否属于实例关系,而不能判断一个对象实例具体属于哪种类型。

instanceof 操作符的问题在于,它假定只有一个全局执行环境。如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的构造函数。如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[0].Array;
var arr = new xArray(1,2,3); // [1,2,3]
arr instanceof Array; // false

针对数组的这个问题,ES5 提供了 Array.isArray() 方法。该方法用以确认某个对象本身是否为 Array 类型,而不区分该对象在哪个环境中创建。

注意:

console.log("1" instanceof String);  //false
console.log(1 instanceof Number);  //false
console.log(true instanceof Boolean);  //false

new Number(1) instanceof Number;  //true
new String('1') instanceof Number;  //true
new Boolean(false) instanceof Number;  //true
  1. constructor

null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。

函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object

function Fn(){};

Fn.prototype=new Array();

var f=new Fn();
console.log(f.constructor===Fn);  //false
console.log(f.constructor===Array);  //true
  1. Object.prototype.toString.call(true)
Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

参考链接

数据类型转换
    https://www.jb51.net/article/136520.htm
    https://www.jb51.net/article/136521.htm
    https://blog.csdn.net/qq2071114140/article/details/92478526
    https://blog.csdn.net/luckydie/article/details/77948097
    https://blog.csdn.net/Doulvme/article/details/83104683
判断数据类型
    https://www.cnblogs.com/onepixel/p/5126046.html
    https://www.cnblogs.com/zt123123/p/7623409.html

正文完
 0