Skip to content Skip to sidebar Skip to footer

Change Array Size By Just Adding Element And No Push Javascript

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: [

Solution 1:

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.

Solution 2:

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.

Solution 3:

Pages in function doSmth() is not in the same namespace as pages in service, wich is service.pages.

Your pages[1] musst be a global declared somewhere else.

However you are initializing pages as an empty (but existing) array: pages: [],

var service = {
    pages: [],
    doSmth: doSmth
};

doSmth();

function doSmth() {
    pages[1] = "abc";
    pages[5] = "def";
}

Post a Comment for "Change Array Size By Just Adding Element And No Push Javascript"