好!欢迎访问迷津渡口 现在时间是: 天气 °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
   支持一下
挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
 点赞
 签到
 表情
 图片
 代码
提交评论

清空信息
关闭评论
videoaulaneri
 videoaulaneri 约 2 小时前回复
#268
<a href="http://www.wowsurffest.com/nike-sb-dunk-low-pro-obsidian-white-shoesk">nike sb dunk low pro obsidian white</a> <a href="http://www.yepigamescom.com/nike-kd-9-r%C3%B8d-and-sort-skoj">nike kd 9 r酶d and sort</a> <a href="http://www.elgintransfer.com/nike-sandals-alle-schwarz-schuheh">nike sandals alle schwarz</a> <a href="http://www.allstuffcats.com/white-and-black-adidas-ultra-boost-shoesk">white and black adidas ultra boost</a> <a href="http://www.mywheelcity.com/michael-kors-bedford-crossbody-sale-mkh">michael kors bedford crossbody sale</a> <a href="http://www.sabalink.com/air-max-90-premium-em-menn-svart-bl%C3%A5-s%C3%B8lv-obuvi">air max 90 premium em menn svart bl氓 s酶lv</a>
[url=http://www.videoaulaneri.com/]videoaulaneri[/url]
ishidesign
 ishidesign 约 8 小时前回复
#267
<a href="http://www.muebleactual.com/bon-march%C3%A9-air-max-2014-tout-noir-chaussuresh">bon march茅 air max 2014 tout noir</a> <a href="http://www.xfullfilmizle.com/nike-classic-cortez-trainers-in-bianca-scarpeh">nike classic cortez trainers in bianca</a> <a href="http://www.mycryptoverse.com/oakland-raiders-carr-jersey-nfli">oakland raiders carr jersey</a> <a href="http://www.blokistand.com/todas-negro-nike-shox-deliver-hombres-zapatosh">todas negro nike shox deliver hombres</a> <a href="http://www.wadeesley.com/nike-hyperdunk-2015-flyknit-low-blanco-azul-zapatosk">nike hyperdunk 2015 flyknit low blanco azul</a> <a href="http://www.dermonenc.com/north-face-black-jacket-with-red-zipper-northfaceh">north face black jacket with red zipper</a>
ishidesign http://www.ishidesign.com/
bgaddiict
 bgaddiict 约 18 小时前回复
#266
<a href="http://www.kaliteankara.com/mens-mizuno-wave-creation-13-white-blue-shoesi">mens mizuno wave creation 13 white blue</a> <a href="http://www.bagsbeat.com/nike-free-run-4.0-hombres-dark-gris-zapatosi">nike free run 4.0 hombres dark gris</a> <a href="http://www.lolalolincoln.com/adidas-pr%C3%B8dator-mi-skoh">adidas pr酶dator mi</a> <a href="http://www.buycharboleps.com/nike-mercurial-vapor-bianca-scarpei">nike mercurial vapor bianca</a> <a href="http://www.androidsmith.com/rosso-sole-converse-scarpej">rosso sole converse</a> <a href="http://www.oheyewear.com/mens-henrik-zetterberg-detroit-red-wings-40-premier-green-2016-st.-patricks-day-reebok-jersey-nflh">mens henrik zetterberg detroit red wings 40 premier green 2016 st. patricks day reebok jersey</a>
bgaddiict http://www.bgaddiict.com/
urbnite
 urbnite 2019-04-19 02:09回复
#265
<a href="http://www.kafsabimoradi.com/mens-contrast-collar-polo-july-30-03_1273859mens-long-sleeve-polo-poloh">mens contrast collar polo july 30 03_1273859mens long sleeve polo</a> <a href="http://www.henryglegg.com/nike-zoom-vomero-8-gr%C3%A5-low-skok">nike zoom vomero 8 gr氓 low</a> <a href="http://www.theillitches.com/under-armour-clutchfit-drive-stephen-curry-orange-gr%C3%BCn-schuheh">under armour clutchfit drive stephen curry orange gr眉n</a> <a href="http://www.thomsank.com/womens-nike-kd-10-yellow-shoesk">womens nike kd 10 yellow</a> <a href="http://www.youdaanl.com/adidas-zx-flux-sort-reflective-skol">adidas zx flux sort reflective</a> <a href="http://www.sactopalooza.com/adidas-tubular-x-r%C3%B8d-and-svart-obuvk">adidas tubular x r酶d and svart</a>
urbnite http://www.urbnite.com/
lyricensemble
 lyricensemble 2019-04-19 01:40回复
#264
<a href="http://www.salesmasterypro.net/nike-air-max-2017-kpu-negro-and-naranja-kush-kurpese">nike air max 2017 kpu negro and naranja kush</a> <a href="http://www.sastafitness.net/nike-roshe-run-dynamic-flywire-qs-negro-kurpesa">nike roshe run dynamic flywire qs negro</a> <a href="http://www.sattonet.net/kobe-9-fundamenntals-chaussuresb">kobe 9 fundamenntals</a> <a href="http://www.savetheastrodome.net/mennns-air-max-lunar-90-gr%C3%A5-r%C3%B8d-obuve">mennns air max lunar 90 gr氓 r酶d</a> <a href="http://www.schildgen.net/nike-air-max-tailwind-8-kvinders-guld-hvid-chaussuresa">nike air max tailwind 8 kvinders guld hvid</a> <a href="http://www.scogblog.net/flyknit-air-max-zero-gituttio-butya">flyknit air max zero gituttio</a>
lyricensemble http://www.lyricensemble.net/
steugenesband
 steugenesband 2019-04-18 17:00回复
#263
<a href="http://www.poradanomada.com/nike-blazer-low-nero-suede-scarpei">nike blazer low nero suede</a> <a href="http://www.njdevsblog.com/air-jordan-retro-11-ni%C3%B1os-hombresta-verde-zapatosh">air jordan retro 11 ni帽os hombresta verde</a> <a href="http://www.theuonline.com/kvinders-nike-cortez-r%C3%B8d-gul-skok">kvinders nike cortez r酶d gul</a> <a href="http://www.myflexijob.com/menn-salomon-gcs-athletic-trail-dark-gr%C3%A5-gr%C3%A5-obuvi">menn salomon gcs athletic trail dark gr氓 gr氓</a> <a href="http://www.myglobalsms.com/adidas-neo-mesh-dark-azul-verde-zapatosl">adidas neo mesh dark azul verde</a> <a href="http://www.playunreal.com/ray-ban-green-polarized-lenses-review-sunglassesh">ray ban green polarized lenses review</a>
steugenesband http://www.steugenesband.com/
cooterscamera
 cooterscamera 2019-04-18 09:05回复
#262
<a href="http://www.hinogi.com/air-jordan-retro-1-womens-red-silver-shoesj">air jordan retro 1 womens red silver</a> <a href="http://www.prontosignsus.com/michael-kors-jet-set-travel-tote-peanut-mkh">michael kors jet set travel tote peanut</a> <a href="http://www.ticahome.com/nike-huarache-ultra-gull-gr%C3%A5-obuvi">nike huarache ultra gull gr氓</a> <a href="http://www.prformusic.com/femminile-nike-zoom-pegasus-31-nero-oro-scarpej">femminile nike zoom pegasus 31 nero oro</a> <a href="http://www.tatilblogu.com/adidas-crazylight-boost-green-pink-shoesh">adidas crazylight boost green pink</a> <a href="http://www.danieladirosa.com/air-jordan-retro-10-azul-blanco-zapatosp">air jordan retro 10 azul blanco</a>
cooterscamera http://www.cooterscamera.com/
swiftgrocer
 swiftgrocer 2019-04-18 06:49回复
#261
<a href="http://www.atrapaniapp.com/nike-air-huarache-oransje-r%C3%B8d-obuvl">nike air huarache oransje r酶d</a> <a href="http://www.maplebeyond.com/nike-air-presto-skull-mens-purple-shoesh">nike air presto skull mens purple</a> <a href="http://www.collisionsix.com/femminile-asics-gel-noosa-tri-10-rosa-arancia-scarpei">femminile asics gel noosa tri 10 rosa arancia</a> <a href="http://www.todololitas.com/under-armour-curry-2-lila-schwarz-schuhej">under armour curry 2 lila schwarz</a> <a href="http://www.jcwjrlaw.com/purdue-boilermakers-new-era-ncaa-classic-shade-neo-39thirty-cap-hath">purdue boilermakers new era ncaa classic shade neo 39thirty cap</a> <a href="http://www.vstsblog.com/femmes-adidas-zx-750-hommesthe-verte-chaussuresh">femmes adidas zx 750 hommesthe verte</a>
swiftgrocer http://www.swiftgrocer.com/
isimdesign
 isimdesign 2019-04-17 04:38回复
#260
<a href="http://www.davidtraina.com/adidas-neo-neon-pink-skot">adidas neo neon pink</a> <a href="http://www.landvoicepro.com/harrison-smith-mens-game-purple-jersey-nike-nfl-minnesota-vikings-home-22-nflt">harrison smith mens game purple jersey nike nfl minnesota vikings home 22</a> <a href="http://www.zipperdude.com/nike-mens-danny-etling-limited-white-road-jersey-new-england-patriots-nfl-5-vapor-untouchable-nflu">nike mens danny etling limited white road jersey new england patriots nfl 5 vapor untouchable</a> <a href="http://www.karlcoates.com/free-run-4.0-wei%C3%9F-zinfandel-kurpesc">free run 4.0 wei脽 zinfandel</a> <a href="http://www.cloisonnes.com/nike-lebron-15-purple-germany-shoeso">nike lebron 15 purple germany</a> <a href="http://www.orsadonna.com/nike-zoom-pegasus-32-rosso-blu-obuvc">nike zoom pegasus 32 rosso blu</a>
isimdesign http://www.isimdesign.com/
citypixxel
 citypixxel 2019-04-17 00:47回复
#259
<a href="http://www.rexpousa.com/nike-air-force-1-flyknit-high-gr%C3%A5-svart-obuvi">nike air force 1 flyknit high gr氓 svart</a> <a href="http://www.dalvadesign.com/adidas-ace-15.1-core-negro-zapatosl">adidas ace 15.1 core negro</a> <a href="http://www.velvetwifi.com/nike-mercurial-superfly-rosso-scarpeh">nike mercurial superfly rosso</a> <a href="http://www.sophiarugby.com/womens-nike-air-max-bw-orange-shoesk">womens nike air max bw orange</a> <a href="http://www.thumbglovepro.com/ray-ban-cats-5000-polarized-sunglasses-sunglassesh">ray ban cats 5000 polarized sunglasses</a> <a href="http://www.ceracustica.com/nike-roshe-bleu-and-blanc-chaussuresl">nike roshe bleu and blanc</a>
citypixxel http://www.citypixxel.com/
顶部留言底部
 00:00/00:00
我想和你虚度时光 - 花房姑娘(9)
  1. 我想和你虚度时光
  2. 花房姑娘
  3. 恋恋风尘
  4. 我喜爱一切不彻底的事物
  5. 我的心里是满的
  6. Long Way
  7. 给少年的歌
  8. 晴日共剪窗
  9. 天上的月你的脸