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>
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
对于用+转换和原生转换性能查看: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
时间: 2024-10-22 05:17:38