zoukankan      html  css  js  c++  java
  • 你见过这些JavaScript的陷阱吗?

    一、成员操作符

    Number.prototype.testFn=function () {
        console.log(this<0, this.valueOf());
    }
    var num = -1;
    num.testFn();  //true -1
    (22).testFn();  //false 22
    22.testFn();  //Uncaught SyntaxError: Invalid or unexpected token
    (-1).testFn();  //true -1
    -1..testFn();  //false 1
    -1.2.testFn();  //false 1.2

    点运算符会被优先识别为数字常量的一部分,然后才是对象属性访问符。

    二、连等赋值

    var a = {n: 1};  
    var b = a; 
    a.x = a = {n: 2};  
    console.log(a.x);  //undefined  
    console.log(b.x);  //{n: 2}

    交换下连等赋值顺序a = a.x = {n: 2};可以发现结果不变,即顺序不影响结果。

    三、强制转换

    var aReg = /^[a-z]+$/;
    aReg.test(null);  //true
    aReg.test();  //true

    test方法的参数如果不是字符串,会经过抽象ToString操作强制转成字符串,因此实际测试的是字符串 "null"和"undefined"。

    四、传参

    "1 2 3".replace(/d/g, parseInt);  //"1 NaN 3"

    实际进行计算的是[1, 0], [2, 2], [3, 4]

    五、为什么给基础类型添加属性不报错但又无效?

    var num = 1;
    num.prop = 2;
    num.prop   //undefined

    num.prop等同于Object(num).prop,也就是说,我们添加属性到一个新建的对象上,与num没任何关系。

    六、运算符优先级

    var str = 'abc'
    console.log('Result is' + (str === 'abc') ? 'Right' : 'Wrong')
    // Right
  • 相关阅读:
    C# 读取计算机CPU,HDD信息
    实现多线程下载文件
    安装SharePoint Server的主机重命名
    SharePoint 2010: Change welcome page on PowerShell
    FW: Solving SharePoint Server -503. The service is unavailable, After installation
    XDocument 使用
    ListBox 控件单击事件
    设计Popup Window
    Listbox Binding ItemsSource
    ListBox item Sort
  • 原文地址:https://www.cnblogs.com/camille666/p/js_trap.html
Copyright © 2011-2022 走看看