Lodash没有办法“删除”

我正在关注我书中的websockets一个例子:

 var _ = require('lodash') var ws = require('ws') var clients = [] exports.connect = function(server) { var wss = new ws.Server({server: server}) wss.on('connection', function(ws) { clients.push(ws) ws.on('close', function() { _.remove(clients, ws) }) }) } exports.broadcast = ... 

上面的代码片段将新的websocket客户端添加到clients数组中。 当客户端closures连接时,它将从列表中删除。 我在_.remove(clients, ws)上收到以下错误:

 TypeError: Object function lodash(value) { // exit early if already wrapped, even if wrapped by a different `lodash` constructor if (value && typeof value == 'object' && value.__wrapped__) { return value; } // allow invoking `lodash` without the `new` operator if (!(this instanceof lodash)) { return new lodash(value); } this.__wrapped__ = value; } has no method 'remove' at WebSocket.<anonymous> (/home/user/Projects/socialapp/websockets.js:15:6) at WebSocket.EventEmitter.emit (events.js:117:20) at WebSocket.cleanupWebsocketResources (/home/user/Projects/socialapp/node_modules/ws/lib/WebSocket.js:926:10) at Socket.EventEmitter.emit (events.js:117:20) at net.js:441:14 at process._tickCallback (node.js:415:13) 

这绝对是在我的书中完成的方式,我不明白为什么我得到这个错误,因为remove方法肯定存在。

编辑:我使用lodash

可能有一些与你的lodash版本有关的问题。 试着这样做:

 var _ = require('lodash') var ws = require('ws') var clients = [] exports.connect = function(server) { var wss = new ws.Server({server: server}) wss.on('connection', function(ws) { clients.push(ws) ws.on('close', function() { clients = _.without(clients, ws) }) }) } 

或者你可以简单地使用普通的旧javascript来做同样的事情

 clients = clients.filter((client) => client !== ws);