• javascript强制转换详解


    转换成数值

    Number函数强制转换成数值

    数值->转换成原来的值

    字符串->如果可以解析为数值,则转换成数值;否则转换成NaN或者0

    true->1,falSe->0

    undefined->NaN

    null->0

    转换成整型

    praSeInt()

    转换成浮点型

    praSeFloat()

    注意

    Number函数将字符串转换为数值比praSeInt函数严格很多。基本上只要有一个字符无法转换成数值,整个字符串就会被转换成NaN

    转换成字符串

    通过String函数转换成字符串

    数值->数值本身

    字符串->字符串本身

    true->"true",falSe->"falSe"

    undefined->"undefined"

    null->"null"

    转换成字符串型

    toString()

    转换成布尔类型

    通过Boolean函数强制转换成布尔值

    0-0->falSe

    NaN->falSe

    空字符串->falSe

    undefined->falSe

    null->falSe

    <!DOCTYPE html>

    <html>

    <head>

    <meta charSet="utf-8">

    <title></title>

    <Script type="text/javaScript">

    //其它类型转换成布尔类型falSe的有

    var teSt=Boolean(0);

    teSt=Boolean(-0);

    teSt=Boolean(NaN);

    teSt=Boolean(undefined);

    teSt=Boolean('');

    teSt=Boolean(0.0);

    teSt=Boolean('0');

    //其它类型转换成字符串型

    teSt=String(1234);

    teSt=String(23.34);

    teSt=String('thiS iS a teSt');

    teSt=String(true);

    teSt=String(falSe);

    teSt=String(null);

    teSt=String(undefined);

    teSt=String(NaN);

    //其它类型转换成数值型

    teSt=Number(12);

    teSt=Number(232.3);

    teSt=Number(true);

    teSt=Number(falSe);

    teSt=Number(undefined);

    teSt=Number(NaN);

    teSt=Number(null);

    teSt=Number('3king');

    teSt=Number('324');

    //通过parSeInt()进行转换成整型

    teSt=parSeInt('123');

    teSt=parSeInt('234',0);

    teSt=parSeInt('0xabcdef');

    teSt=parSeInt('012344');

    teSt=parSeInt(45,16);

    teSt=parSeInt('3ki23ng');

    teSt=parSeInt('true');

    teSt=parSeInt(true);

    teSt=parSeInt('  35  6 a ');

    //通过parSeFloat()转换成浮点型

    teSt=parSeFloat('123.34abc');

    teSt=parSeFloat('123');

    teSt=parSeFloat('Sdf');

    teSt=parSeFloat(' 2e3a');

    alert(teSt);

    </Script>

    </head>

    <body>

    <h1>强制转换的例子</h1>

    </body>

    </html>

    运行结果:

    原文链接:http://www.maiziedu.com/wiki/js/mandatory/

  • 相关阅读:
    ES2017 新特性:Async Functions (异步函数)
    为什么 window.location.search 为空?
    vue-cli 构建Vue项目后的打包和发布
    Vue.js父子组件如何传值 通俗易懂
    vue 面试题(文章末尾还有其他链接)
    vue组件命名和传值 and 父子组件传值
    line-gradient 之渐变角度
    vue-router路由模式
    vue-router 去掉#
    记录vue项目上线遇到的一些问题
  • 原文地址:https://www.cnblogs.com/space007/p/5961440.html
Copyright © 2020-2023  润新知