“Use the array literal notation []” for var os_map = {}

后端 未结 4 1075
梦毁少年i
梦毁少年i 2021-01-02 03:56

I don\'t understand why I get the error message when I run JSLint with a JavaScript file.

I get the message var os_map = {}; Problem at line 28 character 36: Us

4条回答
  •  礼貌的吻别
    2021-01-02 04:12

    The offending line:

    var os_autoload_inputs = new Array('searchInput', 'searchInput2',
                                       'powerSearchText', 'searchText');
    

    JSLint does not expect to see new Array constructor, you should use [] instead:

    var os_autoload_inputs = ['searchInput', 'searchInput2',
                                       'powerSearchText', 'searchText'];
    

    Why? :

    1, Crockford doesn't like new.

    2, The Array object could be overridden:

    Array = {};
    new Array(); // TypeError: Array is not a constructor
    

    3, Usage inconsistencies, e.g.:

    var a = new Array(5); // empty 5 elements array
    var b = [5]; // 1 element array containing the 5 number on index 0
    

    See also:

    • What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
    • What’s wrong with var x = new Array();

提交回复
热议问题