javascript转数据类型的方法:1、根据运算环境自动转换值的数据类型,以满足运算需要;2、使用 toString()、String()、parseInt()等JavaScript内置函数来强制转换数据类型。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
JavaScript是一门动态语言,所谓的动态语言可以暂时理解为在语言中的一切内容都是不确定的。比如一个变量,这一时刻是个整型,下一时刻可能会变成字符串了。虽然变量的数据类型是不确定的,但是各种运算符对数据类型是有要求的。如果运算符发现,运算子的类型与预期不符,就会自动转换类型。
简单来说,JavaScript 能够根据运算环境自动转换值的类型,以满足运算需要。
例:使用加号运算符把值转换为字符串
//把数字转换为字符串 var n = 123; n = n + ""; console.log(typeof n); //返回类型为 string
例:使用乘运算符把字符串转为数值
var n = "123"; n = n * 1; console.log(typeof n); //返回类型为 number
但是在很多情况下需要开发者手动转换数据类型(强制类型转换),以控制运算过程。
1、其他的数据类型转换为String
方式一:toString()方法
调用被转换数据类型的toString()方法,该方法不会影响到原变量,它会将转换的结果返回,但是注意:null和undefined这两个值没有toString,如果调用他们的方法,会报错。
var a = 123 a.toString()//"123" var b = null; b.toString()//"报错" var c = undefined c.toString()//"报错"
采用 Number 类型的 toString() 方法的基模式,可以用不同的基输出数字,例如二进制的基是 2,八进制的基是 8,十六进制的基是 16
var iNum = 10; alert(iNum.toString(2)); //输出 "1010" alert(iNum.toString(8)); //输出 "12" alert(iNum.toString(16)); //输出 "A"
方式二:String()函数
使用String()函数做强制类型转换时,对于Number和Boolean实际上就是调用的toString()方法,
但是对于null和undefined,就不会调用toString()方法,它会将null直接转换为"null",将undefined 直接转换为"undefined"
var a = null String(a)//"null" var b = undefined String(b)//"undefined"
String方法的参数如果是对象,返回一个类型字符串;如果是数组,返回该数组的字符串形式。
String({a: 1}) // "[object Object]" String([1, 2, 3]) // "1,2,3"
2、其他的数据类型转换为Number
方式一:使用Number()函数
下面分成两种情况讨论,一种是参数是原始类型的值,另一种是参数是对象
(1)原始类型值
①字符串转数字
如果是纯数字的字符串,则直接将其转换为数字
如果字符串中有非数字的内容,则转换为NaN
如果字符串是一个空串或者是一个全是空格的字符串,则转换为0
Number('324') // 324 Number('324abc') // NaN Number('') // 0
②布尔值转数字:true转成1,false转成0
Number(true) // 1 Number(false) // 0
③undefined转数字:转成NaN
Number(undefined) // NaN
④null转数字:转成0
Number(null) // 0
⑤Number() 接受数值作为参数,此时它既能识别负的十六进制,也能识别0开头的八进制,返回值永远是十进制值
Number(3.15); //3.15 Number(023); //19 Number(0x12); //18 Number(-0x12); //-18
(2)对象
简单的规则是,Number方法的参数是对象时,将返回NaN,除非是包含单个数值的数组。
Number({a: 1}) // NaN Number([1, 2, 3]) // NaN Number([5]) // 5
方式二:parseInt() & parseFloat()
这种方式专门用来对付字符串,parseInt()一个字符串转换为一个整数,可以将一个字符串中的有效的整数内容取出来,然后转换为Number。parseFloat()把一个字符串转换为一个浮点数。parseFloat()作用和parseInt()类似,不同的是它可以获得有效的小数。
console.log(parseInt('.21')); //NaN console.log(parseInt("10.3")); //10 console.log(parseFloat('.21')); //0.21 console.log(parseFloat('.d1')); //NaN console.log(parseFloat("10.11.33")); //10.11 console.log(parseFloat("4.3years")); //4.3 console.log(parseFloat("He40.3")); //NaN
parseInt()在没有第二个参数时默认以十进制转换数值,有第二个参数时,以第二个参数为基数转换数值,如果基数有误返回NaN
console.log(parseInt("13")); //13 console.log(parseInt("11",2)); //3 console.log(parseInt("17",8)); //15 console.log(parseInt("1f",16)); //31
两者的区别:Number函数将字符串转为数值,要比parseInt函数严格很多。基本上,只要有一个字符无法转成数值,整个字符串就会被转为NaN。
parseInt('42 cats') // 42 Number('42 cats') // NaN
上面代码中,parseInt逐个解析字符,而Number函数整体转换字符串的类型。
另外,对空字符串的处理也不一样
Number(" "); //0 parseInt(" "); //NaN
3、其他的数据类型转换为Boolean
它的转换规则相对简单:只有空字符串("")、null、undefined、+0、-0 和 NaN 转为布尔型是 false,其他的都是 true,空数组、空对象转换为布尔类型也是 true,甚至连false对应的布尔对象new Boolean(false)也是true
Boolean(undefined) // false Boolean(null) // false Boolean(0) // false Boolean(NaN) // false Boolean('') // false
Boolean({}) // true Boolean([]) // true Boolean(new Boolean(false)) // true
【推荐学习:javascript高级教程】
以上是javascript如何转数据类型的详细内容。更多信息请关注PHP中文网其他相关文章!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互动,可及可访问。1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒体综合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityAncccossibility.2)和TagsallowsemplowsemplowseamemelesseamlessallowsemlessemlessemelessmultimedimeDiaiiaemediaiaembedwitWithItWitTplulurugIns.3)

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrevulnerabilityLikeClickLickLickLickLickLickjAckJackJacking.2)

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3汉化版
中文版,非常好用

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中