简体   繁体   English

为什么我的javascript对象的值未定义?

[英]Why is my value of a javascript object undefined?

I keep getting undefined when I attempt to output the objects value via chrome console. 当我尝试通过chrome控制台输出对象值时,我总是变得不确定。 Code: 码:

ws.on('message', function(message) {
     var JSONobj = {"cmd":"updatesb","name":"TestName"};
     console.log('JSON Name Value: %s', message.name); //<--does not work
     console.log('JSON Name Value: %s', JSONobj.name); //<----WORKS!!!!
});

The message argument in ws.on passes {"cmd":"updatesb","name":"TestName"} via websocket communication. ws.on中的message参数通过websocket通信传递{“ cmd”:“ updatesb”,“ name”:“ TestName”}。 The first console output is undefined. 第一个控制台输出未定义。 The second output is TestName. 第二个输出是TestName。 Why is message.name undefined when it should have a value of TestName and how do I get the value from message.name? 为什么当message.name应该具有TestName的值时未定义,以及如何从message.name获取该值?

It sounds like your message parameter is a string, not an object. 听起来您的message参数是一个字符串,而不是一个对象。

You can parse that string as JSON by calling JSON.parse() . 您可以通过调用JSON.parse()将该字符串解析为JSON。

Try: 尝试:

 message.name = 'xxx';
 console.log('JSON Name Value: %s', message.name);

to see if the message.name succeeds. 查看message.name成功。 As others pointed out, message is most likely not what you think. 正如其他人指出的那样, message很可能不是您的想法。

Try also console.log(message); 也尝试console.log(message); and examine the output. 并检查输出。

Also, it may be that the on handler receives more then just the message so the handler should in fact look like function(something_else, message) , but it is hard to know without knowing what ws is. 另外,可能是on处理程序接收到的信息多于消息,因此处理程序实际上应该看起来像function(something_else, message) ,但是如果不知道ws是什么,就很难知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM