zoukankan      html  css  js  c++  java
  • js中的数据类型转换

    JS中一共有七种数据类型,包括五种基本数据类型和两种复杂数据类型

    * 五种基本数据类型
    * string
    * number
    * boolean
    * undefined
    * null
    * 两种复杂数据类型
       * array
    * object

    这里记录一下其他类型转成number、转成string、转成boolean的的方法

    首先介绍一下NaN,NaN是属于number类型的
    1.NaN: not a number,  是一个错误的数学计算的结果
    NaN是number类型中一个特殊的值:表示的是错误的数学计算结果
    var num =  "张三" - 100 ;//NaN  如果一个算术表达式的结果不是一个数字,则得到NaN
    console.log ( num );//NaN
    console.log ( typeof num );//number
    2.NaN与任何数字计算得到的都是NaN
    console.log ( NaN - 100 );//NaN
    3.NaN与任何数字都不等,包含它自身
    console.log ( NaN == 0 );//false
    console.log ( NaN == NaN );//false
    4.检测一个数字是不是NaN
    语法:  isNaN(数据)    结果是布尔类型  true:是NaN  false:不是NaN
    console.log ( isNaN ( 1 ) );//false
    console.log ( isNaN ( NaN ) );//true

    转成number:
    1.转换整数:parseInt(数据)
       //parseInt原理:从左往右依次解析字符,遇到非数字字符结束解析,并且将解析好的整数返回
    2.转换小数:parsetFloat(数据)
       //parseFloat原理:与parseInt一致,唯一的区别就是可以识别字符中的第一个小数点
    3.转数字:Number(数据)
       //Number原理:(1)可以转整数和小数  (2)只要有任何一个非数字字符就会得到NaN
    数据.toFixed(2)方法,可以对数据保留两位小数,数据要为number类型才能调用,不然会报错,返回结果类型为string



    转成string:
    1.常用:  String(数据),可以转换undefined与null
    2.变量名.toString(),不能转换undefined与null,程序会报错



    转成boolean:
    只有一种方式: Boolean(数据)

    false:只有八种情况会得到fasle
    0,  -0 ,   undefined ,  null ,  '' (空字符串) , false , NaN,   document.all()

    console.log ( Boolean ( 0 ) )//false
    console.log ( Boolean ( - 0 ) )//false
    console.log ( Boolean ( undefined ) )//false
    console.log ( Boolean ( null ) )//false
    console.log ( Boolean ( "" ) )//false
    console.log ( Boolean ( NaN ) )//false
    console.log ( Boolean ( false ) )//false
    console.log ( Boolean ( document.all () ) )//false

    true:除开这八种情况之外的任何数据

     
     
     
  • 相关阅读:
    一个好的时间函数
    Codeforces 785E. Anton and Permutation
    Codeforces 785 D. Anton and School
    Codeforces 510 E. Fox And Dinner
    Codeforces 242 E. XOR on Segment
    Codeforces 629 E. Famil Door and Roads
    Codeforces 600E. Lomsat gelral(Dsu on tree学习)
    Codeforces 438D The Child and Sequence
    Codeforces 729E Subordinates
    【ATcoder】D
  • 原文地址:https://www.cnblogs.com/zhuangwf/p/11124094.html
Copyright © 2011-2022 走看看