在Javascript函数参数中获取未定义的值(Get undefined value in Javascript function parameter)

编程入门 行业动态 更新时间:2024-10-27 11:29:07
在Javascript函数参数中获取未定义的值(Get undefined value in Javascript function parameter) var sockets = []; function findSocketByUID(uid){ var index = findIndexByUID(uid); if(index == -1) return null; return sockets[index]; } socket.on('chat message', function(msg){ if(msg.to == 'all'){ io.emit('chat message', msg); }else{ var socket_to = findSocketByUID(msg.to); if(socket_to){ socket_to.emit("chat message", msg); }else{ socket.broadcast.emit("chat message", msg); } } });

嗨,这是我的Node.JS应用程序的一部分,使用参数msg.to调用findSocketByUID,这是一个字符串值。 但为什么函数findSocketByUID中的参数uid未定义? 如何正确调用findSocketByUID传递参数?

编辑:我在这一行添加一个断点:

var socket_to = findSocketByUID(msg.to);

我的msg看起来像这样:

“{”to“:”a27efd3f-ee63-413a-20ae-527419fab246“,”content“:”giuh“,”time“:”2016-06-06T11:27:11Z“,”from“:”683C2782-A575 -4154-9F78-CAD6B74AB19D“}”

var sockets = []; function findSocketByUID(uid){ var index = findIndexByUID(uid); if(index == -1) return null; return sockets[index]; } socket.on('chat message', function(msg){ if(msg.to == 'all'){ io.emit('chat message', msg); }else{ var socket_to = findSocketByUID(msg.to); if(socket_to){ socket_to.emit("chat message", msg); }else{ socket.broadcast.emit("chat message", msg); } } });

Hi, this is part of my Node.JS application, findSocketByUID is called with an argument msg.to, which is a string value. But why parameter uid in function findSocketByUID is undefined? How do I call findSocketByUID correctly to pass an argument?

Edit: I add a breakpoint at this line:

var socket_to = findSocketByUID(msg.to);

and my msg looks like this:

"{ "to" : "a27efd3f-ee63-413a-20ae-527419fab246", "content" : "giuh", "time" : "2016-06-06T11:27:11Z", "from" : "683C2782-A575-4154-9F78-CAD6B74AB19D" }"

最满意答案

编辑中显示的msg似乎是一个JSON字符串,而不是一个实际的对象(它在大括号外面有引号)。 字符串不具有.to属性。

您需要使用JSON.parse()将其转换为实际对象,以便您可以访问其属性。

The msg shown in your edit seems to be a string of JSON, not an actual object (it has quote marks outside the curly brackets). A string won't have a .to property.

You'll need to use JSON.parse() to convert it to an actual object so that you can access its properties.

更多推荐

本文发布于:2023-08-06 13:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448852.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   未定义   Javascript   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!