好!欢迎访问迷津渡口 现在时间是: 天气 °C ~ °C

迷津渡口

越感到迷惑 越接近真理

javascript加法和文本转换成数字详解

javascript加法可以是数字相加:

1 + 2 = 3

也可以是文本相加:

"1" + "2" = "12"

如果文本和数字相加,必定变成文本相加:

1 + "2" = "1" + "2" = "12"

Javascript会根据上下文进行相对应的加法计算,但需要计算的是数字,现在还是文本怎么做呢?


一般把文本转换成数字有三种方法:

函数转换强制类型转换弱类型自动转换


函数转换

javascript提供了parseInt()和parseFloat()两个函数将文本转换为数字。

parseInt(string,[base]):将文本转换成整型数字

常用两个参数,一个是文本参数,一个是可选参数:基参数,一般默认是十进制。

如果文本参数包含进制前缀,可省略后面的参数,但设置后面的参数可覆盖前面的前缀:

二进制前缀:0b

八进制前缀:0  

十进制前缀:0d(一般省略)

十六进制前缀:0x


// 默认十进制
parseInt("1234");       // returns 1234
parseInt("1234blue");   // returns 1234
parseInt("22.5");       // returns 22
// 前缀
parseInt("0xA");        // returns 10
parseInt("010");        // returns 8
// 参数
parseInt("AF", 16);     // returns 175
parseInt("10", 2);      // returns 2
parseInt("10", 8);      // returns 8
parseInt("10", 10);     // returns 10
// 包含前缀0但使用参数
parseInt("010");        // returns 8
parseInt("010", 8);     // returns 8
parseInt("010", 10);    // returns 10
// 第一个字符不是数字,转换失败
parseInt("blue168");    // returns NaN

parseFloat(string):将文本转换成浮点类型数字

只有十进制的模式,不能选择其他进制,也不能用前缀使用其他进制。

// 默认十进制
parseFloat("1234blue"); // returns 1234.0
parseFloat("22.5");     // returns 22.5
parseFloat("22.34.5");  // returns 22.34
// 前缀不生效,只能十进制
parseFloat("0908");     // returns 908.0
parseFloat("0xA");      // returns 0.0
// 第一个字符不是数字,转换失败
parseFloat("blue168");  // returns NaN

注意:

文本转成数字时只能取从第一个字符开始为数字,直到不是数字为止的一段。

因此,第一个字符如果不是数字,则转换不能成功,将返回NaN,转换失败。


强制类型转换

强制类型转换可将其他类型的数据强制转换成需要的类型,将文本转换成数字:Number(string)。

强制类型转换转换的是整个文本而不是部分文本,因此文本不是正确数字则返回NaN:

// 前面几个其实不算字符串,也列出来好了,注意不含双引号""
Number(false);           // returns 0
Number(true);            // returns 1         
Number(undefined);       // returns NaN
Number(null);            // returns 0
// 文本为正确数字
Number("5.5");           // returns 5.5
Number("56");            // returns 56
// 文本虽然包含数字但不是正确数字
Number("5.6.7");         // returns NaN


弱类型自动转换

弱类型自动转换是利用js会根据上下文自动转换变量,例如字符串变量没有乘法运算,当字符串变量和数字相乘时会自动转换成数字变量,看下例。但这种方法不推荐,不可控。

var x="12.123";          // x是文本变量"12.123"
var x=x*1;               // x是数字变量12.123
var x=x+1;               // x是数字变量13.123


终于写完了,小指指头都写累了,如果本文对你有用,欢迎转载,记得点赞哦~

点赞1
   支持一下
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
 点赞
 签到
 表情
 图片
 代码
提交评论

清空信息
关闭评论
thebatchseven
 thebatchseven 约 15 小时前回复
#137
<a href="http://www.cpbetas.com/herre-nike-air-huarache-gr%C3%B8n-orange-schuheg">herre nike air huarache gr酶n orange</a> <a href="http://www.horecasummit.com/nike-kobe-10-gr%C3%B8nn-screen-kurpesc">nike kobe 10 gr酶nn screen</a> <a href="http://www.kosahudson.com/nike-air-max-90-sneakerboot-hvid-s%C3%B8lv-obuvg">nike air max 90 sneakerboot hvid s酶lv</a> <a href="http://www.namkala.com/nike-zoom-structure-19-rojo-p%C3%BArpura-scarpee">nike zoom structure 19 rojo p煤rpura</a> <a href="http://www.qubellinfo.com/adidas-prossoator-sl-pro-direct-butya">adidas prossoator sl pro direct</a> <a href="http://www.sulukcum.com/air-max-2015-kvinners-bl%C3%A5-chaussuresf">air max 2015 kvinners bl氓</a>
thebatchseven http://www.thebatchseven.com/
rawbiofast
 rawbiofast 约 16 小时前回复
#136
<a href="http://www.thebiarritz.com/air-jordan-retro-28-gr%C3%B8n-lyser%C3%B8d-skok">air jordan retro 28 gr酶n lyser酶d</a> <a href="http://www.voydnet.com/nike-kd-8-high-blu-cielo-blu-scarpeh">nike kd 8 high blu cielo blu</a> <a href="http://www.foneandlone.com/nike-kobe-12-rosso-nero-scarpei">nike kobe 12 rosso nero</a> <a href="http://www.roomwhiz.com/what-is-tom-brady-jersey-number-nflh">what is tom brady jersey number</a> <a href="http://www.riffsurfers.com/coach-drawstring-logo-monogram-large-coffee-totes-coachh">coach drawstring logo monogram large coffee totes</a> <a href="http://www.davidmgaines.com/femminile-air-jordan-retro-10-bianca-viola-scarpeh">femminile air jordan retro 10 bianca viola</a>
[url=http://www.rawbiofast.com/]rawbiofast[/url]
carbonitegear
 carbonitegear 2019-02-15 09:44回复
#135
<a href="http://www.turkayambalaj.com/lebron-14-sort-ice-mod-scarpee">lebron 14 sort ice mod</a> <a href="http://www.wensemble.com/nike-mercurialx-finale-grigio-gituttio-obuvc">nike mercurialx finale grigio gituttio</a> <a href="http://www.coldwaterapps.com/nike-cortez-venta-hombres-scarpea">nike cortez venta hombres</a> <a href="http://www.enescomert.com/mujeres-nike-air-huarache-blanco-p%C3%BArpura-chaussuresg">mujeres nike air huarache blanco p煤rpura</a> <a href="http://www.evelynreynoso.com/nike-air-max-excellerate-4-premium-maschio-in-esecuzione-scarpa-kurpese">nike air max excellerate 4 premium maschio in esecuzione scarpa</a> <a href="http://www.michsmallbiz.com/jordan-10-powder-blau-kaufen-online-obuva">jordan 10 powder blau kaufen online</a>
carbonitegear http://www.carbonitegear.com/
rebeccastaste
 rebeccastaste 2019-02-14 20:15回复
#134
<a href="http://www.evolutionecig.com/mens-nike-flyknit-roshe-run-green-purple-runninge">mens nike flyknit roshe run green purple</a> <a href="http://www.georginabauer.com/air-jordan-18-varsity-rot-robin-schuhea">air jordan 18 varsity rot robin</a> <a href="http://www.bootsoffprice.com/femmes-nike-kd-7-noir-gris-scarpeb">femmes nike kd 7 noir gris</a> <a href="http://www.theprintjobs.com/nike-air-max-2019-green-uk-shoeso">nike air max 2019 green uk</a> <a href="http://www.dbajournal.com/new-nike-free-run-3-5.0-rosa-gr%C3%B8nn-kvinners-sko-up-kurpesc">new nike free run 3 5.0 rosa gr酶nn kvinners sko up</a> <a href="http://www.procomedian.com/nike-air-zoom-skates-white-zapatost">nike air zoom skates white</a>
rebeccastaste http://www.rebeccastaste.com/
poshandpearls
 poshandpearls 2019-02-14 16:38回复
#133
<a href="http://www.bhcsboosters.com/womens-nike-huarache-utility-black-denmark-shoeso">womens nike huarache utility black denmark</a> <a href="http://www.denisgoulart.com/nike-free-flyknit-4.0-kvinders-bl%C3%A5-gr%C3%A5-kurpesb">nike free flyknit 4.0 kvinders bl氓 gr氓</a> <a href="http://www.donggeomdo.com/on-sale-nike-air-vapormax-flyknit-20-dark-grey-zapatost">on sale nike air vapormax flyknit 20 dark grey</a> <a href="http://www.ozoessaouira.com/girls-high-converse-shoesz">girls high converse</a> <a href="http://www.annomaplexel.com/herren-asics-gel-lyte-5-lila-himmelblau-schuheb">herren asics gel lyte 5 lila himmelblau</a> <a href="http://www.bringribben.com/nike-navy-blue-womens-charles-haley-backer-nfl-94-dallas-cowboys-t-shirt-nflu">nike navy blue womens charles haley backer nfl 94 dallas cowboys t shirt</a>
poshandpearls http://www.poshandpearls.com/
fishmackerel
 fishmackerel 2019-02-13 20:57回复
#132
<a href="http://www.seymourdugan.com/herren-nike-free-run-2-rosa-gold-schuhei">herren nike free run 2 rosa gold</a> <a href="http://www.dkstekstil.com/hombres-nike-blazer-gris-rosado-zapatosp">hombres nike blazer gris rosado</a> <a href="http://www.thegillssell.com/nike-zoom-structure-18-gr%C3%A5-hvid-skoi">nike zoom structure 18 gr氓 hvid</a>
fishmackerel http://www.fishmackerel.com/
ecofunshop
 ecofunshop 2019-02-13 01:20回复
#131
<a href="http://www.anthillprague.com/nike-zoom-pegasus-31-dam%C3%A4nner-wei%C3%9F-blau-scarped">nike zoom pegasus 31 dam盲nner wei脽 blau</a> <a href="http://www.bisbeegrille.com/air-jordan-retro-4.5-gull-bl%C3%A5-butya">air jordan retro 4.5 gull bl氓</a> <a href="http://www.chipchak.com/nike-kobe-7-gr%C3%BCn-party-chaussuresf">nike kobe 7 gr眉n party</a> <a href="http://www.maruldeaur.com/nike-air-max-1-gris-rouge-butya">nike air max 1 gris rouge</a> <a href="http://www.pepinmystep.com/lebron-12-orange-and-bl%C3%A5-jay-schuhef">lebron 12 orange and bl氓 jay</a> <a href="http://www.redtokill.com/ralph-lauren-pony-polo-blu-arancia-polou">ralph lauren pony polo blu arancia</a>
ecofunshop http://www.ecofunshop.com/
industrialegy
 industrialegy 2019-02-12 09:31回复
#130
<a href="http://www.tkbelazig.com/nike-dunks-blu-scarpel">nike dunks blu</a> <a href="http://www.swiftgrocer.com/nike-dunk-pink-sky-blue-shoesj">nike dunk pink sky blue</a> <a href="http://www.warrnamboolag.com/michael-kors-brooke-medium-leather-shoulder-bag-mkh">michael kors brooke medium leather shoulder bag</a> <a href="http://www.paineesq.com/nike-air-max-1-kvinners-gr%C3%A5-bl%C3%A5-obuvi">nike air max 1 kvinners gr氓 bl氓</a> <a href="http://www.gemmatyndall.com/nike-sb-stefan-janoski-max-femminile-oro-rosso-scarpej">nike sb stefan janoski max femminile oro rosso</a> <a href="http://www.cestreaming.com/womens-nike-flyknit-lunar-2-white-purple-shoesh">womens nike flyknit lunar 2 white purple</a>
industrialegy http://www.industrialegy.com/
harpiabd
 harpiabd 2019-02-12 05:46回复
#129
<a href="http://www.intotheglos.com/nike-air-max-lunar-1-team-rojo-now-chaussurese">nike air max lunar 1 team rojo now</a> <a href="http://www.myslinc.com/jordan-1-royal-bl%C3%A5-ajko-scarpef">jordan 1 royal bl氓 ajko</a> <a href="http://www.shamankin.com/nfl-youth-houston-texans-nike-olive-salute-to-service-sideline-therma-pullover-hoodie-nfls">nfl youth houston texans nike olive salute to service sideline therma pullover hoodie</a> <a href="http://www.singingtoons.com/ralph-lauren-m%C3%A6nd-shirt-polo-orange-oxford-in-custom-regular-fit-polox">ralph lauren m忙nd shirt polo orange oxford in custom regular fit</a> <a href="http://www.snowdayrealty.com/angels-of-anaheim-56-kole-calhoun-green-salute-to-service-stitched-mlb-jersey-nflz">angels of anaheim 56 kole calhoun green salute to service stitched mlb jersey</a> <a href="http://www.totesoftware.com/herren-nike-free-flyknit-3.0-schwarz-orange-kurpesd">herren nike free flyknit 3.0 schwarz orange</a>
harpiabd http://www.harpiabd.com/
atrapaniapp
 atrapaniapp 2019-02-10 20:43回复
#128
<a href="http://www.teamdalarna.com/air-jordan-retro-2-purple-blue-shoesh">air jordan retro 2 purple blue</a> <a href="http://www.syairshamyoun.com/mujeres-nike-air-max-thea-p%C3%BArpura-naranja-zapatosp">mujeres nike air max thea p煤rpura naranja</a> <a href="http://www.fizalisfresh.com/nike-blazer-rojo-naranja-zapatosk">nike blazer rojo naranja</a> <a href="http://www.fsscas.com/north-face-m-gotham-jacket-northfaceh">north face m gotham jacket</a> <a href="http://www.imagimp.com/nike-hypershift-grau-himmelblau-schuhej">nike hypershift grau himmelblau</a> <a href="http://www.burmamaritime.com/ua-micro-g-torch-alle-bl%C3%A5-skoh">ua micro g torch alle bl氓</a>
atrapaniapp http://www.atrapaniapp.com/
顶部留言底部
 00:00/00:00
我想和你虚度时光 - 花房姑娘(9)
  1. 我想和你虚度时光
  2. 花房姑娘
  3. 恋恋风尘
  4. 我喜爱一切不彻底的事物
  5. 我的心里是满的
  6. Long Way
  7. 给少年的歌
  8. 晴日共剪窗
  9. 天上的月你的脸