下面是读取事件属性的JavaScript代码:
function webSockStart() { // onclick() of a button
document.getElementById("button").disabled = true;
var ws = new WebSocket("ws://127.0.0.1:3000/websock");
ws.onmessage = function (evt) {
console.log(evt.data)
console.log(evt.data["Key"]) // undefined
console.log(evt.data["Val"]) // undefined
};
}
console.log(evt.data)
给出一个字符串"{"Key":"ab","Val":"cd"}"
(通过websocket接收)
var map = new Map(JSON.parse(evt.data))
给出错误:Uncaught TypeError: object is not iterable(cannot read property Symbol(Symbol.Iterator))
如何将此字符串转换为地图对象并读取属性?console.log(evt.data["Key"])
答案 0 :(得分:1)
您需要先对其进行解析,然后才能访问
let str = `{"data" : {"Key":"ab","Val":"cd"}}`
let obj = JSON.parse(str)
console.log(obj.data['Key'])