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
  • 相关阅读:
    串的模式匹配问题
    游戏手柄directinput编程
    Hibernate的generator属性的意义
    MySQL——基础入门
    IEbug——li标签之间的空隙
    struts2 jar包详解
    hibernate自动建库(MySQL)
    hibernate参数一览表
    js中的逻辑运算符
    hibernate的离线关联(多级)查询
  • 原文地址:https://www.cnblogs.com/camille666/p/js_trap.html
Copyright © 2011-2022 走看看