How are javascript arrays implemented?

后端 未结 9 759
天命终不由人
天命终不由人 2020-12-05 17:09

Namely, how does the following code:

var sup = new Array(5);
sup[0] = \'z3ero\';
sup[1] = \'o3ne\';
sup[4] = \'f3our\';
document.write(sup.length + \"
相关标签:
9条回答
  • 2020-12-05 18:04

    To add to tvanfosson's answer: In ECMA-262 (the 3.0 specification, I believe), arrays are simply defined as having this behavior for setting properties (See 15.4.5.1). There's no general mechanism underlying it (at least as of now) - this is just how it's defined, and how javascript interpreters must behave.

    0 讨论(0)
  • 2020-12-05 18:09

    A JavaScript array is an object just like any other object, but JavaScript gives it special syntax.

    arr[5] = "yo"
    

    The above is syntactic sugar for

    arr.insert(5,"yo")
    

    which is how you would add stuff to a regular object. It's what is inside the insert method that changes the value of arr.length

    See my implementation of a customArray type here: http://jsfiddle.net/vfm3vkxy/4/

    0 讨论(0)
  • 2020-12-05 18:09

    As other people have mentioned, a property in JavaScript can basically act as both as getter and a setter of your array (or string or other inputs).

    As a matter of fact, you might try this yourself:

    const test=[1,2,3,4,5]
    test.length = 3
    console.log(test) // [1,2,3]
    test.length = 5
    console.log(test) // guess what happens here!
    

    As far as I know, arrays in JS do not work exactly like associative arrays and you have elements which are put in memory as contiguously as possible (given that you can have arrays of mixed objects), depending on the JS engine you are considering.

    As a side note, I am a bit baffled that the most voted answer keeps spreading the over-simplified myth (or half-truth) of "everything being an object in JavaScript"; that is not exactly true, otherwise you will never study primitives, for example.

    Try to do this:

    const pippi = "pippi"
    pippi.cat = "cat"
    console.log(pippi.cat) // will it work? Throw an error? Guess why again
    

    Spoiler: the string is wrapped in a throwaway object for that specific operation on the second line, then in the following one you are just going to access a property of the primitive which is not there (provided you did not play with String.prototype or the like), so you get undefined.

    0 讨论(0)
提交回复
热议问题