[英]Lodash has no method 'remove'
我正在從我的書中遵循有關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
訴3.10.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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.