• 你见过这些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
  • 相关阅读:
    python 垃圾回收机制
    @property 取代getter setter方法
    ==值相等 is同一性
    循环获取文件名,拼接路径打印
    python 闭包
    python生成器
    hadoop集群环境搭建之zookeeper集群的安装部署
    hadoop集群环境搭建之安装配置hadoop集群
    hadoop集群环境搭建准备工作
    linux下安装jdk
  • 原文地址:https://www.cnblogs.com/camille666/p/js_trap.html
Copyright © 2020-2023  润新知