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

    1.通过typeof查看数据类型

    typeof 3.14                   // 返回 number
    typeof NaN                    // 返回 number
    typeof "John"                 // 返回 string 
    typeof false                  // 返回 boolean
    typeof [1,2,3,4]              // 返回 object
    typeof {name:'John', age:34}  // 返回 object
    typeof new Date()             // 返回 object
    typeof function () {}         // 返回 function
    typeof myCar                  // 返回 undefined(如果myCar没有声明)
    typeof undefined              // 返回 undefined
    typeof null                   // 返回 object

    typeof的返回只有number、string、boolean、object、function、undefined五种类型

    如果要查看的是数组、对象、日期、或者null,返回值都是object,无法通过typeof来判断他们的类型

    2.通过constructor属性返回构造函数

    (1234).constructor                   //function Number() { [native code] }
    NaN.constructor                      //function Number() { [native code] }
    'hello'.constructor                  //function String() { [native code] }
    false.constructor                    //function Boolean() { [native code] }
    [1,2,3,4].constructor                //function Array() { [native code] }
    {name:'John', age:34}.constructor    //function Object() { [native code] }
    new Date().constructor               //function Date() { [native code] }
    function(){}.constructor             //function Function() { [native code] }

    constuction属性返回的构造函数有七种,unll和undefined没有构造函数

    3.自动类型转换

    数字 + 字符串 : 将数字转化为字符串,再与后面字符串的进行拼接

    数字 + 布尔值:true转化为1,false转化为0,再与数字进行相加

    字符串 + 布尔值:按照字符串进行拼接

    document.getElementById("demo").innerHTML = myVar;
    myVar = {name:"Fjohn"}  // toString 转换为 "[object Object]"
    myVar = [1,2,3,4]       // toString 转换为 "1,2,3,4"
    myVar = new Date()      // toString 转换为 "Fri Jul 18 2014 09:08:55 GMT+0200"

    4.数字、布尔值、日期强制转化为字符串

    String(123)、(123).toString()都可将数字转化为字符串

    String(true)、false.toString()都可将布尔值转化为字符串

    String(new Date()) 、(new Date()).toString()都可将日期转化为字符串

    5.数字类型的字符串、布尔值、日期强制转化为数字

    Number('3.14')可将字符串3.14转化为数字3.14,Number('')返回0,Number("99 88")返回NaN  

    Number(false)返回0,Number(true) 返回1

    d = new Date(),Number(d)和d.getTime()可将日期转换为数字

    parseInt( ) 将浮点数、字符串类型的数字、以数字开头的字符串转化为整数,转换失败时会得到NaN

    parseFloat()强制转换为浮点数

    6.eval():将字符串强制转换为表达式并返回结果,例如eval('1+4')=5

  • 相关阅读:
    20201016---不做清单
    20201014--增删改查
    20201013--什么是真实的自己?
    多态
    继承
    关键字
    分类思想
    常用的linux命令
    九九乘法表
    稀疏数组
  • 原文地址:https://www.cnblogs.com/Forever77/p/10247986.html
Copyright © 2011-2022 走看看