I am trying to understand why in nodejs array splice does not work on an associate array.
var a = [];
a['x1'] = 234234;
a['x2'] = 565464;
console.log("Init-------");
showIt();
a.splice(0, 1);
console.log("After splice-------");
showIt();
delete a['x1'];
console.log("After delete-------");
showIt();
function showIt(){
var keys = Object.keys(a);
var len = keys.length;
var i=0;
while (i < len) {
console.log( ' ' + i + ' ------------ ' + keys[i] );
i++;
}
}
Results:
Init-------
0 ------------ x1
1 ------------ x2
After splice-------
0 ------------ x1
1 ------------ x2
After delete-------
0 ------------ x2
Splicing the array does nothing...
Same results in a browser...
Update:
Splice works as expected when the array is defined as:
var a = ['x1','x2','x3'];
console.log("Init-------");
console.log(a);
a.splice('x1', 1);
console.log("After splice-------");
console.log(a);
Looks like in the first example, the array is being treated as if is was defined as a object {}
in the 2nd, it's being treated more like an array.
To the Moderators:
This is not really a question about spare arrays, it is more of a question of an array which is starting at 0 and growing sequentially to 10 million over a period of days. As it is growing the array is being deleted from so that around 1000 items are in the array at one time.
I am considering forcing the use of hash tables by using non-numeric keys or defining as a object {}
so that the it acts like a sparse array.
In the end, I am not sure if it matters...
splice
works onarrays
orarray-like
objects, in the first example it is doing exactly what is expected of it as per spec In the second you aredelet
ing a property from an object (an array is still an object) – Kaysermyarray[crazyId]
in the case with nodejs which I am researching now I need to maintain an array of websocket connections. The index will start at 0 and increase with each new connection and when the connection is dropped , it is removed from the array. I am worried that v8 might keep the deleted array items in memory and cause a leak. – Unitarysplice
to delete it then that array no longer holds a reference to it. here will be no leak there. That doesn't mean to say that you are not holding some other reference to the port object somewhere else in your code. The only limit with the array is that the indexes are from 0 to 2^32-1. And ofcourse binding more than one connection to a single port number may need a little more thinking. – KayserObject
with properties and usingdelete
to remove them either. – Kayser