美文网首页
JavaScript学习使用

JavaScript学习使用

作者: 浩仔_Boy | 来源:发表于2017-09-29 14:39 被阅读10次

    弱类型的特性#

    var num1 = 66;
    var num2 = "66";
    num1+num2 = "6666";
    num1-num2 = 0;
    num2-num2 = 0;
    

    数据类型

    number、string、boolean、null、undefined、object。其中前五种是原始数据类型。
    object包括,Function、Date、Array……。
    

    类型转换

    typeof 操作符
    typeof "John"                 // 返回 string 
    typeof 3.14                   // 返回 number
    typeof NaN                    // 返回 number
    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 null                   // 返回 object,这里是历史遗留问题,当时向改为null,但是导致众多网站出现问题。
    
    constructor 操作符
    "John".constructor                 // 返回函数 String()  { [native code] }
    (3.14).constructor                 // 返回函数 Number()  { [native code] }
    false.constructor                  // 返回函数 Boolean() { [native code] }
    [1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
    {name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
    new Date().constructor             // 返回函数 Date()    { [native code] }
    function () {}.constructor         // 返回函数 Function(){ [native code] }
    
    instanceof 操作符
    instanceof返回的是一个布尔值,如:
    var a = {};
    alert(a instanceof Object);  //true
    var b = [];
    alert(b instanceof Array);  //true
    instanceof只能用来判断对象和函数,不能用来判断字符串和数字等,比如
    var b = '123';
    alert(b instanceof String);  //false
    alert(typeof b);  //string
    var c = new String("123");
    alert(c instanceof String);  //true
    alert(typeof c);  //object
    另外,用instanceof可以判断变量是否为数组
    

    try-catch嵌套

    <script language="javascript">  
    try  
    {  
        document.forms.input.length;  
    }  
    catch(exception)  
    {  
        alert("try异常发生"); 
        try  
        {  
            document.forms.input.length  
        }  
        catch(exception2)  
        {  
            alert("catch异常发生");  
        }  
    }  
    finally  
    {  
        alert("执行finally"); 
    }  
    </script> 
    执行顺序为:try异常发生》》》catch异常发生》》》执行finally
    

    JS的严格模式

    严格模式是JavaScript中的一种特殊执行模式,修复了部分语言上的不足,提供了更强的错误检查,并增加了安全性。
    
    使用的方式:在文件头或者方法内部使用'use strict'
    注意:
    1.不允许是用with,否则会报SyntaxError
    2.不允许未声明的变量被赋值
    3.arguments变为参数的静态副本
    4.delete参数、函数名,会报SyntaxError;delete不可配置的属性的时候,会报TypeError
    5.对象字面量重复属性名会报错SyntaxError,如var o = {a:1,b:2};
    6.禁止八进制的字面量,如console.log(0123);
    7.eval独立作用域
    8.eval、arguments变为关键字,不能作为变量、函数名
    

    相关文章

      网友评论

          本文标题:JavaScript学习使用

          本文链接:https://www.haomeiwen.com/subject/vylvextx.html