5 ms·
Sorry, NN2 does not agree, it overwrites `length`: function MyArray() { this.length = 0; } var a = new MyArray(); alert(a[0]) // 0 ... alert(
by sergeykish 6y ago
Sorry, NN2 does not agree, it overwrites `length`:
function MyArray() {
this.length = 0;
}
var a = new MyArray();
alert(a[0]) // 0
...
alert( a[0] ); // "frist"
alert( a.length ); // "frist"
alert( a.pop() ); // JavaScript Error: length is not a numeric literal.
alert( a.length );
How clever - https://www.javaworld.com/article/2077150/using-javascript-s-built-in-objects.html?page=2 https://www.javaworld.com/article/2077150/using-javascript-s... - all you have to do is count from 1
- masswerk 6y agoYou are correct, once again, all properties were available both by property name (if used in an associative context) and by numeric index. Since we assigned 'length' already in the constructor, we would have to accommodate for this, i.e., start counting at 1. Turns out, my recollections are a bit on the rosy side… :-) Edit: This should work: function MyArray() { this.length = 0; } function arrayPop() { return this[this.length--]; } function arrayPush( value ) { return this[++this.length] = value; } var a = new MyArray(); a.pop = arrayPop; a.push = arrayPush; a.push('a'); a.push('b'); alert( a[1] ); // 'a' for (var i = 1; i <= a.length; i++) alert( a[i] ); at which point it is much simpler to do: function MyArray() {}; var a = new MyArray(), aLength = 0; a[aLength++] = 'a'; a[aLength++] = 'b'; for (var i = 0; i < aLength; i++) alert( a[i] ); var b = new MyArray(), bLength = 0; // etc which is also, what was actually used.