Js隐式转换笔记整理

2018-08-13 07:46:09来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

1.js的数据类型:
        Number、Boolean、String、Undefined、Null、Symbol(es6新定义的)和Object(ps:Array是特殊的Object)
        typeof返回6种类型:number  boolean  string  object   undefined function 
        
        ps:s是undefined是因为是一个未初始化的变量
2.转换规则:
          对象——>字符串——>数值——>布尔
    eg.
         []==true;  //false     []转换为字符串'',然后转换为数值0,true直接转换为数值1,所以不相等,输出false
         []==false //true     []先转换为字符串'',然后转换为数值0,false直接转换为数值0,相等,输出true
         ![]==false //true       ![]直接转换为布尔值再取反,转换为布尔值时,除空字符串(''),NaN,0,null,undefined这几个之外返回的都是true,取反false则转换为0;false转换为数值0,相等,输出true
         undefined==null //true    undefined和null比较返回true,二者和其他值比较返回false
         Number(null)  //0
 3.常见的隐式转换
        以加号运算时,String和其他类型时,其他类型都会转换为String;其他情况,都转换为Number类型。
        ps:
        1.Undefined转换为Number时为NaN,任何Number与NaN相加都为NaN,而NaN并不等于它自身。也就是说NaN!==NaN,据说isNaN并不可靠。
        2.加感叹号后,转换为Boolean类型为false的有:null,0,'',undefined,NaN,false
        
        3.number()和parseInt()都可以将对象转化为Number类型,Number函数要比parseInt函数严格很多。基本上,只要有一个字符无法转换为数值,整个字符串就会被转为NaN
        
        Number类型会先调用valueOf(),String类型会先调用toString(),如果结果是原始值,则返回原始值,否则继续用toString或valueOf(),继续计算,若不是原始值,则抛出一个类型错误。
        eg.
        
        {}+[]   //js在运行时,将第一次{}认为是空的代码块,相当于   +[] 
        []+[]  //表示字符串""
        另外:
        +[]===0
         -[]===0
        ~[]===-1   //~[]按位非空数组,其值为-1
        ~-~[]===-2
        ~-~-~-~-~[]===-5
        ~-~-~-~-~[]+~[]===-6
        ~+~[]===0
        ~+~+~[]===-1
        ~+~+~+~[]===0
        Ps:~表示按位取反,有一个规律,~x=-(x+1)
        eg.    ~-5=4         ~9=-10
4.其他
        toString:
        [1].toString();    //"1"
        [1,2,3].toString();    //"1,2,3"
        ["a",1,"b",2].toString();    //"a,1,b,2"
        ToNumber:
        
        stackoverflow给了一些关于第二个变成NaN的解释。
         To provide further proof that this toString() conversion happens before the ToNumber conversion, we can actually modify Array.prototype.toString to provide a different result, and any ToNumber conversions will use that modified result.
1 Array.prototype.toString=function(){
2     var n=0;
3     for(var i=0;i<this.length;i++){
4         n+=this[i];
5     }
6     return n;
7 };
         Here I've replaced the toString on Array.prototype with a function that sums the Array. Obviously you don't want to do this, but we can show how we will now get a different result.
1     Number([1,2,3]); //6
2     +[1,2,3];   //6
         So now you can see that the ToNumber conversion of our Array that would previously have resulted in NaN is now resulting in the sum of the items in the Array.
        重写原型后:
        
        emmm,都是从别人那里整理来的,如果错了还请指正,留给自己以后翻看。
        
 
 
 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:js基本语法之 值类型(数据类型)(变量类型)

下一篇:jQuery 对象 与 原生 DOM 对象 相互转换