I know the universal way of changing an array's size is to use .push()
.
However, today I saw a piece of code in angularJS that does something like this:
var service = {
pages: [],
doSmth: doSmth
};
doSmth();
function doSmth() {
service.pages[1] = "abc";
service.pages[5] = "def";
}
I ran the debugger on the browser and found that before doSmth()
is called, pages[1]
is undefined, but after that, pages[1]
is assigned the value without any error.
How is this possible?
Change array size by just adding element and no push javascript.
Arrays can either hold primitive values or object values. An ArrayList can only hold object values. You must decide the size of the array when it is constructed. You can't change the size of the array after it's constructed.
The opposite of push() (as the question is titled) is pop() .
That's just the magic that JavaScript allows. If you come from a language like Java or C, this may seem like a weird idea, but you can set the value of any index in the array at any time, and the array will expand to that size!
Consider:
var t = [];
t.length === 0;
t[10000] = 'value';
t.length === 10001;
JavaScript just handles this behind the scenes. It's worth mentioning that this behavior is not specific to JavaScript. This is seen a bit in other interpreted languages as well. Ruby, for example, allows you to do the same.
Additionally in JavaScript, length
is a writeable attribute of arrays, so you can easily truncate or clear an entire array:
var t = [1];
t[4] = 0;
t === [1, undefined, undefined, undefined, 0];
t.length = 2;
t === [1, undefined];
t.length = 0;
t === [];
Setting the length to 0 is one of the fastest and simplest ways to clear an array. It might not be the most intuitive solution, but it's my go-to.
An array in JavaScript is just an object with some special properties. Essentially, they are just objects with positive, integer property names. There are some other key differences, but the idea is that you could do this:
var obj = { };
obj['1'] = 'abc';
So you can do the same with an array.
However! You shouldn't. Modern JavaScript engines usually optimize arrays by backing them with fast, native implementations. By setting indexes that are not currently allocated will de-optimize your code into something more like an object, which is much slower.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With