JavaScript中的冷知識(持續更新中……)

本文將記錄一些JavaScript中容易出錯的點,由於本人知識有限,所以文章將採取持續更新的方式。本文的JavaScript會涉及瀏覽器端和服務器端的Node.js。可能有點混雜,等文章豐富了再整理吧。您也可以補充一些自己容易犯的錯誤。如有錯誤,請不吝指正。

  1. JavaScript = ECMAScript+DOM+BOM

  2. void 0===undefined,實際上void 任何東西都等於undefined

  3. NaN!==NaNNaN是唯一一個自身和自身不相等的東西

    var a=NaN;
    console.log(a==a)//false
    console.log(a!==a)//true
  4. isNaN不等同於Number.isNaN()。二者行爲是不同的:前者針對所有數據類型,也就是說會對不屬於Number類型的參數使用Number轉型,而Number.isNaN()方法是ES6新增,只針對Number類型,其他數據類型都會返回false

    Number.isNaN(NaN)//true
    Number.isNaN('NaN')//false
    
    isNaN(NaN)//true
    isNaN('NaN')//true
  5. eval雖然是全局方法,但不等同於window.eval

    var color='red';
    function test(){
      var color='blue';
      eval('console.log(color)');
      window.eval('console.log(color)');
      with(window){
        eval('console.log(color)');
      }
    }
    test()
    //outputs:
    //blue
    //red
    //red
  6. 在全局作用域下使用var和不使用var定義變量是有差別的:前者的[[Configurable]]值爲false,這意味着不能使用delete刪除,就算又重新被window.variable賦值,仍然不能被刪除;而後者等同於直接在window上定義屬性。可以被刪除。

    var color='red';
    window.color//red
    window.color='blue'
    color//blue
    delete window.color//false
    
    other=1//等同於window.other=1
    window.other//1
    delete other//true 等同與delete window.other
  7. JSON不支持undefined

  8. parseInt()的第二個參數表示轉換時使用的基數,也就是按多少進制解析數據,其有效取值範圍爲2-36(數字0-9和字母a-z共36個字符可用),不設置或設爲0會按10進制處理。設置的數不在這個界限會返回NaN。而toString()的傳遞參數的範圍在2 -36之間,傳入其他參數會報錯。

    parseInt(100,0)     //100
    parseInt(100,-5)    //NaN
    parseInt(100,36)    //1296
    parseInt(100,37)    //NaN
    (1293).toString(36) //"zx"
    (1296).toString(0)  //Uncaught RangeError: toString() radix argument must be between 2 and 36(…)
  9. JavaScript中的最小數>0

    Number.MAX_VALUE<Infinity           //true
    Number.MIN_VALUE                    //5e-324
    Number.MIN_VALUE>0                  //true
    Number.MIN_SAFE_INTEGER             //-9007199254740991
    Number.MIN_SAFE_INTEGER<0           //true
    Number.POSITIVE_INFINITY==Infinity  //true
    Number.NEGATIVE_INFINITY==-Infinity //true
  10. Function構造函數不會形成閉包

    function test(){
        var color='red';
        var f=new Function('console.log(color)')
        f()
    }
    test()
    //Uncaught ReferenceError: color is not defined
    
    function test(){
        var color='red';
        var f=function(){console.log(color)}
        f()
    }
    test()//red
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章