美文网首页
JS 里的数据类型转换

JS 里的数据类型转换

作者: elsa919 | 来源:发表于2019-01-18 15:57 被阅读19次

    一、数据类型转换

     

    不同数据类型之间转换方法:

    (一)、任意数据类型转为string

    1.number转为string

    例如:var n = 1

          n.tostring()   //1+’ ’空字符串       //全局方法:window.String(1)

          ‘1’

    2.boolean转为string

    例如:var b = true

          b.tostring()   //true+’ ’空字符串//全局方法:window.String(true)

          ‘true’

    3.Null转为string

    例如:var c =null

          c.tostring()    //null+’ ’空字符串//全局方法:window.String(null)

    报错/‘null’’

    4.undefined转为string

    例如:var c =undefined

          c.tostring()                   //undefined+’ ’空字符串

    //全局方法:window.String(undefined)

    报错//’undefined’

    5.object转为strings

    例如:var object = {‘name’: ‘frank’}

          object.tostring()    //obj+’ ’空字符串//全局方法:window.String({})

          ‘[object  Object]’

    1+1=2

    1+’1’数字1和字符串1不能相加(不同数据类型不能相加)

    1+’1’=11    1+’1’= (1).tostring()+’1’=’1’+’1’=11

     

     

    (二、)任意数据类型转为boolean

    1.Number转为boolean

    例如:boolean(1)   // !!1

               True

    注意:number转为boolean只有两个值是false,即0 , NaN,其他number转为boolean的值都为true

    2.String转为boolean

    例如:(1)boolean(‘’)   // !!’’指空字符串

                        False

               (2)boolean(‘     ’)   // !!’    ’指非空字符串

                         True

    注意:string字符串转为boolean只有一个值是false,即空字符串’’,其他string字符串转为boolean的值都为true

    3.object转为boolean

    例如:(1)boolean({})   //{}空对象

                       True

    (2)boolean([])   // !![]空数组

             True

    (3)boolean(function(){})   // !!function(){}空函数

             True

    注意:object对象转为boolean所有值都为true,这里说的对象包括对象.数组.函数。

    4.null转为boolean

    例如:boolean(null)   // !!null

    False

    5.undefined转为boolean

    例如:boolean(undefined)   // !!undefined

    False

    总结:其他数据类型转为boolean,只有5个值是假值(falsy值),即0 , NaN , ‘’空字符串,null, undefined

    (三、)任意数据类型转为number如何转换?

    例如:’1’转换为1,有以下几种方法:

    (1)Number(‘1’)    === 1

    (2)parseInt(‘1’ , 10)    === 1   考试常见第二种

    (3)parseFloat(‘1.23’)   ===1.23

    (4)‘1’ - 0 ===1    ‘1.23’- 0 ===1.23既有parseInt的功能,又有parseFloat的功能

    (5)+ ‘1’  ===  1      + ‘-1’ === -1

    parse是解析的意思

    二、关于内存的理解

    1.内存分为代码区和内存区,内存区又包括左内存Stack栈,右内存Heap堆,数字以64位存储,字符以16位存储。ECMAScript这样规定

    2.值分为:(1)简单的数据类型 number/string/null/undefined/symbol,直接存储在Stack(2)复杂的数据类型object, 存Heap地址,存储在Stack

    三、浅拷贝和深拷贝的区别

    1.深拷贝

    举例:var a = 1

          Var b = a

          b = 2

    问答:a的值为多少?a = 1

    结论:

    (1)无论b的值怎么改变,a的值都不受影响,始终是1,这种情况称为深拷贝

    (2)除了object以外的基本类型/简单赋值就是属于深拷贝

    2.浅拷贝

    举例:var a = {name:‘a’}

          Var b = a

          b.name = ‘b’ 

    问答:a.name的值为多少?a.name = ‘b’ 

    结论:

    (1)b的值改变a的值也改变,这种情况称为浅拷贝

    (2)除了object以外的基本类型/简单赋值就是属于深拷贝

    相关文章

      网友评论

          本文标题:JS 里的数据类型转换

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