欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javaScript把其它類型轉(zhuǎn)換為Number類型

 更新時(shí)間:2019年10月13日 15:30:27   作者:雪旭  
在本篇文章里小編給大家整理的是關(guān)于javaScript把其它類型轉(zhuǎn)換為Number類型的相關(guān)文章,有需要的朋友們學(xué)習(xí)下。

一:基本類型

字符串

把字符串轉(zhuǎn)換為數(shù)字,只要字符串中包含任意一個(gè)非有效數(shù)字字符(第一個(gè)點(diǎn)除外)結(jié)果都是NaN,空字符串會(huì)變?yōu)閿?shù)字零

console.log(Number("12.5")); //12.5
console.log(Number("12.5px")); //NAN
console.log(Number("12.5.5px"));//NAN
console.log(Number(""));//0

布爾

console.log(Number(true));//1
console.log(Number(false));//0
console.log(isNaN(false));//false 是有效數(shù)字

null和undefined

console.log(Number(null));//0
console.log(Number(undefined));//NaN

二:引用數(shù)據(jù)類型

把引用數(shù)據(jù)類型轉(zhuǎn)換為數(shù)字是先把它基于toString()轉(zhuǎn)換為字符串,再轉(zhuǎn)換為數(shù)字

console.log(Number({num:"10"}));//NaN
console.log(Number({}));//NaN ({num:"10"}).toString();是"[object Object]" 是非有效數(shù)字字符所以是NaN
console.log(Number([]));//0 [].toString()是""所以轉(zhuǎn)為數(shù)字是0
console.log(Number([12]));//12 [12].toString()是"12"所以轉(zhuǎn)為數(shù)字是12
console.log(Number([12,23]));//NaN [12].toString()是"12,23"里面的","是非有效數(shù)字字符所以是NaN

相關(guān)面試題

let a=10+null+true+[]+undefined+'騰訊'+null+[]+10+false;
console.log(a)//11undefined騰訊null10false

null變?yōu)閿?shù)字是0,true是1,[]變?yōu)閿?shù)字,先要經(jīng)歷變?yōu)榭兆址?遇到字符串,啥也別想了,直接變?yōu)樽址唇?

當(dāng)去掉undefined前面的[]結(jié)果就變成了NaN騰訊null10false

以上就是本次介紹的javaScript把其它類型轉(zhuǎn)換為Number類型全部知識(shí)點(diǎn)內(nèi)容,感謝大家的學(xué)習(xí)和對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論