Lodash没有方法'删除'

时间:2015-12-28 17:29:36

标签: javascript node.js websocket 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数组中。当客户端关闭连接时,它会从列表中删除它。我在_.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 v。3.10.1

1 个答案:

答案 0 :(得分:1)

可能存在与您的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);