码迷,mamicode.com
首页 > Web开发 > 详细

JS里面的一元加号操作符

时间:2015-08-15 00:06:24      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

1.转换为时间戳

技术分享
<p>
        <label>getTime:</label><input id="getTime" type="text" readonly value=""/>
    </p>
    <p>
        <label>valueOf:</label><input id="valueOf" type="text" readonly value=""/>
    </p>
    <p>
        <label>unaryPlus +:</label><input id="unaryPlus" type="text" readonly value=""/>
    </p>
    <p>
        <label>now:</label><input id="now" type="text" readonly value=""/>
    </p>
View Code
技术分享
        var now = new Date(),
            now_time = Date.now();
        var getTime=document.getElementById("getTime"),
            unaryPlus=document.getElementById("unaryPlus"),
            valueOf=document.getElementById("valueOf"),
            onow=document.getElementById("now");
        onow.value= now_time;
        getTime.value=now.getTime();
        unaryPlus.value= +now;
        valueOf.value= now.valueOf();

        console.log(now.getTime() === now.valueOf())//true
        console.log(now.getTime() === +now)//true
        console.log(now.getTime() === now_time)//true
View Code

对于用+转换和原生转换性能查看:http://jsperf.com/gettime-vs-unaryplus

2.强制为数字

+true //1
+null //0
+"" //0
+"3.0" //3
+"4.2" //4.2
特殊:
+"3asdf"  //NAN
parseInt("02a2sdf", 10)  //2

举例:
20 + "15" //2015
20 + +"15" //35
 

JS里面的一元加号操作符

标签:

原文地址:http://www.cnblogs.com/xqling/p/4731470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!