[英]How do I find an object by object inside a javascript array
I'm storing websocket connections inside an array. 我将websocket连接存储在数组中。 These are objects.
这些是对象。 And I'd like to remove a connection from the array when the connection is closed.
而且,当连接关闭时,我想从阵列中删除连接。
Is there any way I can find which connection object matches the closing connection and unset it? 有什么办法可以找到哪个连接对象与关闭的连接匹配并取消设置?
I don't think indexOf
works, right? 我认为
indexOf
无效,对吗? Because the value is an object... 因为值是一个对象...
......................................... .........................................
here's some code 这是一些代码
var connections = [];
websocketServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
connection.on('message', function(message){
if(message.type !== 'utf8')
return;
var msg = JSON.parse(message.utf8Data);
if(msg.txt == 'something'){
connections.push(connection);
}
});
connection.on('close', function(connection) {
// here remove connection object from connections array
});
});
You can do indexOf
then splice
你可以先做
indexOf
然后splice
var index = connections.indexOf(connection);
if(~index) connections.splice(index,1);
Use underscore.js and call _.isEqual(object, other);
使用underscore.js并调用
_.isEqual(object, other);
Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. Underscore是JavaScript的实用程序带库,它提供了Prototype.js(或Ruby)中期望的许多功能编程支持,但没有扩展任何内置的JavaScript对象。 It's the tie to go along with jQuery's tux, and Backbone.js's suspenders.
这是与jQuery的晚礼服和Backbone.js的吊带一起使用的纽带。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.