这就是我试图通过WebSocket从Leap Motion设备的帧中获取特定元素的方法。
var webSocket = require('ws');
ws = new webSocket('ws://127.0.0.1:6437');
ws.on('message', function(data, flags) {
var frame = JSON.parse(data);
var id = frame.hands;
var pos = id[0];
console.log(pos);
});
JSON对象如下所示:Leap Motion Sample Frame
我收到此错误。
Sanjeet-Suhags-MacBook-Pro:LeapJS sanjeetsuhag$ node index.js
/Users/sanjeetsuhag/Developer/Node/LeapJS/index.js:7
var pos = id[0];
^
TypeError: Cannot read property '0' of undefined
at WebSocket.<anonymous> (/Users/sanjeetsuhag/Developer/Node/LeapJS/index.js:7:14)
at WebSocket.emit (events.js:98:17)
at Receiver.self._receiver.ontext (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/WebSocket.js:697:10)
at Receiver.opcodes.1.finish (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/Receiver.js:397:14)
at Receiver.expectHandler (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/Receiver.js:384:31)
at Receiver.add (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/Receiver.js:93:24)
at firstHandler (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/WebSocket.js:673:22)
at process._tickCallback (node.js:419:13)
出了什么问题?感谢。
答案 0 :(得分:0)
如果未检测到指针,hands
数组为空,只需将代码更改为:
ws.on('message', function(data, flags) {
var frame = JSON.parse(data);
var id = frame.hands;
if (id.length === 0)
return;
var pos = id[0];
console.log(pos);
});