1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/** Set - New Array */ const users = []; /** * Add - New Element/Item */ users.push({ id: socket.id, name: 'Visitor'}); /** * Find - Index of Element */ var foundIndex = users.findIndex(x => x.id == socket.id); /** * Update/Add - New Data an Founded Element */ users[foundIndex].name = data.name; /** * Remove */ users.splice(foundeIndex, 1); |
Example from My Home Hobby Project:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const users = []; nsp.on('connection', (socket) => { console.log('Kullanici :' + socket.id + 'Baglandi'); users.push({ id: socket.id, name: 'Visitor'}); socket.on('sendUserData', (data) => { console.log('Server => ' + data.name + ' Connected.'); var foundIndex = users.findIndex(x => x.id == socket.id); users[foundIndex].name = data.name; nsp.emit('updateUserList', users); }); socket.on('sendMessage', (data) => { console.log(data); }); socket.on('disconnect', ()=> { var foundIndex = users.findIndex(x => x.id == socket.id); users.splice(foundIndex, 1); nsp.emit('updateUserList', users); }); console.log(users); }); |