Javascript Array extension

后端 未结 3 1072
再見小時候
再見小時候 2021-01-28 11:47

Just wonder. I have extended javascript Array object using its prototype as follows:







        
3条回答
  •  星月不相逢
    2021-01-28 12:09

    Crockford does a great job of explaining this on his site and in his videos. It sounds like you are abusing the Array type by using it as a hash table. In which case you will need to do the following

    From Crockford:

    JavaScript has very nice notational conveniences for manipulating hashtables.

    var myHashtable = {};
    

    This statement makes a new hashtable and assigns it to a new local variable. JavaScript is loosely typed, so we don't use type names in declarations. We use subscript notation to add, replace, or retrieve elements in the hashtable.

    myHashtable["name"] = "Carl Hollywood";
    

    There is also a dot notation which is a little more convenient.

    myHashtable.city = "Anytown";
    

    The dot notation can be used when the subscript is a string constant in the form of a legal identifier. Because of an error in the language definition, reserved words cannot be used in the dot notation, but they can be used in the subscript notation.

    You can see that JavaScript's hashtable notation is very similar to Java's object and array notations. JavaScript takes this much farther: objects and hashtables are the same thing, so I could have written

    var myHashtable = new Object();
    

    and the result would have been exactly the same.

    There is an enumeration capability built into the for statement.

    for (var n in myHashtable) {
        if (myHashtable.hasOwnProperty(n)) {
            document.writeln("

    " + n + ": " + myHashtable[n] + "

    "); } }

    I beleive the jquery .each code does this for you but I'm not 100% sure.

    If you are using an actual Array and want to use it properly, you should just do

    for (var i = 0; i < myArray.length; i++)
    {
        alert(myArray[i]);
    }
    

提交回复
热议问题