zoukankan      html  css  js  c++  java
  • JavaScript中七种数据类型·中·一

    Standing on Shoulders of Giants;

    说到JavaScript里的类型很容易就让人想起 42和"42",分别是string型和number型,但是他们可以直接进行运算。这就是Js里面有趣又让人头疼的问题了。JavaScript会进行强制类型转换

    下面我们就正式来认识一下JS中的类型吧:

    1、内置类型

    JavaScript有七种内置类型:

    2、类型检测 typeof

    1 typeof undefined === 'undefined';//true
    2 typeof 'abc' === 'string';//true
    3 typeof 123 === 'number';//true
    4 typeof true === 'boolean';//true
    5 typeof {a:'test'} === 'object';//true
    6 typeof Symbol() === 'symbol';//true
    

    一共七种类型,六种都在上面了,还有谁呢?对,还有null。
    null 比较特殊,用typeof 判断会出问题

        typeof null === 'object';//true
    

    照理说应该是typeof null 的返回值应该是'null',但是这个bug确实在js语言中客观存在。
    如果要判断一个值是否是null,可以用下面的这种方式来检测:

     var a = null;
     if(!a&&typeof a === 'object'){
         //此刻说明a的值是null
         
     }
    

    null是“假值”,也是唯一一个用typeof检测会返回‘object’的基本类型值。
    另两种种特殊情况是function和array

    typeof function a(){} === 'function';//true
    typeof [1,2,3] === 'object';//object
    

    函数和数组都是对象的内置类型,算是object的‘子类型’。
    函数可以拥有属性,例如a.length;//0;

    2、值和类型

    JavaScritp中的变量是没有类型的,只有值才有。变量可以随时持有任何类型的值
    语言引擎不要求变量总是持有与其初始值同类型的值。一个变量可以先被赋值为字符串后重新赋值为数字,不会报错。

    3、undefined和undeclared

    变量在未持有值的时候为undefined,此时typeof 返回 ' undefined ';
    已在作用域中声明但没有赋值的变量返回值是undefined,在作用域中没声明过的变量返回值是:ReferenceError: 变量名 is not defined

     var a ;
     a;//undefined
     b;//ReferenceError : b is not defined
    

    这里有一个要注意的点:typeof 对于未声明过和声明过未赋值的变量返回结果都是‘undefined’

    4、如何在程序中检查变量是否已存在

    if(typeof myTest !== 'undefined'){
        console.log('myTest已经存在')
    }
    if(typeof atob === 'undefined'){
        atob = function(){}
    }
    

    还可以用‘依赖注入’设计模式,就是将依赖通过参数显示地传递到函数中:

    function doSomethingCool(FeatureXyz){
        var helper = FeatureXyz || function(){}
        var val = helper();
    }
    

    5、总结:

    1、JavaScript中其中内置类型:null、undefined、string、number、boolean、object、symbol
    2、变量没有类型,但它们持有的值有类型,类型定义了值的行为特征
    3、undefined:声明过未赋值变量;undeclared:没声明过

  • 相关阅读:
    AX 2012 Security Framework
    The new concept 'Model' in AX 2012
    How to debug the SSRS report in AX 2012
    Using The 'Report Data Provider' As The Data Source For AX 2012 SSRS Report
    Deploy SSRS Report In AX 2012
    AX 2012 SSRS Report Data Source Type
    《Taurus Database: How to be Fast, Available, and Frugal in the Cloud》阅读笔记
    图分析理论 大纲小结
    一文快速了解Posix IO 缓冲
    #转载备忘# Linux程序调试工具
  • 原文地址:https://www.cnblogs.com/angfl/p/10265787.html
Copyright © 2011-2022 走看看