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

    基本数据类型:

    string、number、boolean、null、undefined

    引用数据类型:

    object、array、function

    使用typrof检测数据:

    typeof "123" // 返回 string
    typeof 3.14 // 返回 number
    typeof NaN // 返回 number
    typeof false // 返回 boolean
    typeof [1,2,3] // 返回 object
    typeof {name:'123'} // 返回 object
    typeof function () {} // 返回 function
    typeof myCar // 返回 undefined (如果 myCar 没有声明)
    typeof null // 返回 object
    typeof undefined //返回undefined
    object数据类型的无法通过typeof来区分

     使用constructor属性,返回所有js变量的构造函数

    "123".constructor // 返回函数 String() { [native code] }
    (3.14).constructor // 返回函数 Number() { [native code] }
    false.constructor // 返回函数 Boolean() { [native code] }
    [1,2,3,4].constructor // 返回函数 Array() { [native code] }
    {name:'123'}.constructor // 返回函数 Object() { [native code] }
    new Date().constructor // 返回函数 Date() { [native code] }
    function () {}.constructor // 返回函数 Function(){ [native code] }

    将字符串转为数字:Number()

    Number('') //返回0
    Number(' ') //返回0
    Number('1 3') //返回NaN
    Number('13') //返回13

    一元运算符+:将变量转换为数字

    var x = +’123s‘ // x是NaN
    var x = +’123‘ // x是123

    自动类型转换:

    5 + null // 返回 5 null 转换为 0
    "5" + null // 返回"5null" null 转换为 "null"
    5 + ’1‘ //返回‘51’
    "5" + 1 // 返回 "51" 1 转换为 "1"
    "5" - 1 // 返回 4 "5" 转换为 5

    原始值转换为数字转换为字符串转换为布尔值
    false 0 "false" false
    true 1 "true" true
    0 0 "0" false
    1 1 "1" true
    "0" 0 "0" true
    "000" 0 "000" true
    "1" 1 "1" true
    NaN NaN "NaN" false
    Infinity Infinity "Infinity" true
    -Infinity -Infinity "-Infinity" true
    "" 0 "" false
    "20" 20 "20" true
    "hello" NaN "hello" true
    [ ] 0 "" true
    [20] 20 "20" true
    [10,20] NaN "10,20" true
    ["hello"] NaN "hello" true
    ["hello","Google"] NaN "hello,Google" true
    function(){} NaN "function(){}" true
    { } NaN "[object Object]" true
    null 0 "null" false
    undefined NaN "undefined" false
  • 相关阅读:
    Netbackup 命令之bplist
    定时任务crond生产实战经验
    数据分析的应用
    数据分析的三个常见误区
    Linux文件系统目录结构
    Linux系统介绍
    两款傻瓜化小白爬虫工具推荐
    时间管理利器之一:RescueTime 自动记录时间
    Lambda 表达式
    IDEA 配置 不需要提交的文件 保证git代码干净
  • 原文地址:https://www.cnblogs.com/wcx-20151115-hzz/p/14978445.html
Copyright © 2011-2022 走看看