Domanda

Vale a dire, come fa il seguente codice:

var sup = new Array(5);
sup[0] = 'z3ero';
sup[1] = 'o3ne';
sup[4] = 'f3our';
document.write(sup.length + "<br />");

uscita '5' per la lunghezza, quando tutto quello che hai fatto è impostato vari elementi?

Il mio 'problema' con questo codice è che io non capisco come length modifiche senza chiamare un getLength() o di un metodo setLength(). Quando faccio una delle seguenti:

a.length
a['length']
a.length = 4
a['length'] = 5

su un oggetto non-array, si comporta come una matrice dict / associativo. Quando faccio questo l'oggetto array, ha un significato speciale. Quale meccanismo in JavaScript permette che questo accada? Ha javascript hanno qualche tipo di sistema di proprietà che si traduce

a.length
a['length']

in "get" metodi e

a.length = 4
a['length'] = 5

in "set" metodi?

È stato utile?

Soluzione

Tutto in JavaScript è un oggetto. Nel caso di un Array, il length proprietà restituisce la dimensione dell'area di memorizzazione interna per elementi indicizzati dell'array. Alcuni di confusione può entrare in gioco in quanto il [] operatore lavora per entrambi gli argomenti numerici e di stringa. Per un array, se lo si utilizza con un indice numerico, restituisce / imposta l'elemento indicizzato previsto. Se lo si utilizza con una stringa, restituisce / imposta la proprietà denominata sull'oggetto array - a meno che la stringa corrisponde ad un valore numerico, quindi restituisce l'elemento indicizzato. Questo perché in JavaScript indici di matrice sono costretti a stringhe da un implicito toString() chiamata. Francamente, questo è solo un altro di quelle cose che ti fa grattare la testa e dire "di JavaScript, questo, questo è il motivo per cui ridono di te."

L'attuale rappresentazione sottostante può differire tra i browser (o non può). Non vorrei fare affidamento su qualcosa di diverso l'interfaccia che viene fornito quando si lavora con esso.

E 'possibile trovare maggiori informazioni su array Javascript al MDN .

Altri suggerimenti

Per aggiungere alla risposta di tvanfosson: In ECMA-262 (la specifica 3.0, credo), le matrici sono semplicemente definiti come avere questo comportamento per l'impostazione delle proprietà (vedere 15.4.5.1). Non c'è alcun meccanismo generale alla base (almeno fin d'ora) -. Questo è solo come è definito, e come interpreti JavaScript deve comportarsi

Questo dipende da cosa si intende fare con esso.

[].length è "magico".
In realtà non restituisce il numero di elementi nella matrice. Restituisce il più grande indice di insediato nella matrice.

var testArr = [];  testArr[5000] = "something";  testArr.length; // 5000

Ma il metodo dietro il setter è nascosto nel motore stesso.
Alcuni motori in alcuni browser ti consentirà di accedere ai loro implementazioni di quelle magiche-metodi. Altri saranno tenere tutto completamente bloccato.

Quindi non si basano su metodi defineGetter e defineSetter, o anche, in realtà, __proto__ metodi, se non si sa quali browser si sa ci si rivolge, e che non si sono.

Questo cambierà in futuro, in cui le applicazioni opt-in scritti in ECMAScript Avanti / 6 avranno accesso a più.

ECMAScript browser 5-compliant stanno già cominciando a offrire get e set metodi magici negli oggetti e non c'è più a venire ... ... ma probabilmente è un po 'lontano prima di poter scaricare il supporto per oldIE e tonnellata di smartphone, et cetera ...

E 'importante sapere che quando si fa sup['look'] = 4; non si utilizza un array associativo, ma piuttosto modificare le proprietà sul sup oggetto. È equivalente a sup.look = 4; dato che è possibile aggiungere dinamicamente immobili in oggetti JavaScript in qualsiasi momento. sup['length'] farebbe per un'uscita esempio 5 nel primo esempio.

Se avete intenzione di implementare oggetti con accesso agli array-like, il Array Mozilla articolo centro dev è una grande risorsa. Purtroppo non conosco la profondità nei dettagli di implementazione Array ma ci sono un sacco di dettagli in questo articolo.

Array object inherits caller, constructor, length, and name properties from Function.prototype.

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/

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.

Characteristics of a Javascript Array

  1. Dynamic - Arrays in Javascript can grow dynamically .push
  2. Can be sparse - For e.g. array[50000] = 2;
  3. Can be dense - For e.g. array =[1, 2, 3, 4, 5]

In Javascript, it is hard for the runtime to know whether the array is going to be dense or sparse. So all it can do is take a guess. All implementations use a heuristic to determine if the array is dense or sparse. For example, code in point 2 above, can indicate to javascript runtime that this is likely a sparse array implementation. If the array is initialised with an initial count, this could indicate that this is likely a dense array.

When the runtime detects that the array is Sparse, it is implemented in a similar way to an object. So instead of maintaining a contiguous array, a key/value map is built.

For more Reference - https://www.quora.com/How-are-javascript-arrays-implemented-internally

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top