Miguel Araujo
Miguel Araujo

Reputation: 13

.splice(x,1) not working

I giving my first steps using Node JS and things were going ok until I faced a strange behaviour that I cannot neither understand nor find an workaround for it. It should be so simple, everything is well documented and I can find so many examples of this working that I may be missing something very obvious, unfortunately. After loosing almost 2 days around this I decided to ask for some help... thanks in advance.

I am trying to store objects (clientID, socket info) in an array and want to remove an object when the connection gets lost.

I've build a small subset of my code that replicates the behaviour.

var socket = require('socket.io');

var machines = [];
var mach1 = [new socket(), new socket()];
var mach2 = [new socket(), new socket()];
var mach3 = [new socket(), new socket()];

machines["357973049420265"] = mach1;
machines["357973049420266"] = mach2;
machines["357973049420267"] = mach3;

console.log("Before : " + Object.keys(machines));
machines.splice(0,1);
console.log("After  : " + Object.keys(machines));

The result is:

Before : 357973049420265, 357973049420266, 357973049420267 
After  : 357973049420265, 357973049420266, 357973049420267

Any ideas?

Thx

Upvotes: 1

Views: 283

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

machines is an array, so you are setting "357973049420265" -- a string value -- as a key. .splice will only alter numeric keys.

I'm not sure what you are trying to achieve, but you either want to use machines = {} and remove properties via delete or use .push to add array elements to get .splice to work.

If you used an object you could do delete machines[Object.keys(machines).slice(0, 1)] to do what this code seems to be trying to do, but your ultimate goal is unclear.

Upvotes: 2

Related Questions