gpt4 book ai didi

javascript - JS 切片、拆分和解析

转载 作者:行者123 更新时间:2023-11-30 11:35:14 24 4
gpt4 key购买 nike

我有一个 Raspberry Pi Zero 位于室外,带有 DH22 温度/湿度传感器。该传感器通过 UDP 传递读数,该读数由 NodeRed 中的 UDP 输入 Node 接收。

来自传感器的数据是一个字符串,格式如下:

"(64.4000015258789, 14.899999618530273)"

我对 JS 的经验不多,但自从开始使用 NodeRed 以来,我学到了很多东西。传递到函数中的消息被描述为:“消息作为一个名为 msg 的 JavaScript 对象传入。按照惯例,它将具有包含消息正文的 msg.payload 属性。”经过多次尝试和错误,这是我认为应该有效的代码 - 但它不...

var str = msg.payload;

var th = str.slice(0, -1);
th = th.split(",");

msg.payload[0] = parseFloat(th[0]);
msg.payload[1] = parseFloat(th[1]);

return [ msg.payload[0], msg.payload[1] ];

但是,我得到这个错误:

"TypeError: Cannot assign to read only property '_msgid' of ("

从错误消息看来,我正在尝试为 msg.payload (msg.payload[0]) 的第一个字符赋值 - 在本例中是字符“(”。我有点困惑.

编辑:在 NodeRed 中,我使用具有两个输出的函数 Node 。因此,应该将提到的输入字符串剥离、拆分并解析为 float ,然后返回到每个输出。要将数据发送到两个不同的输出,您需要:

return [ data1, data2 ]

Data1输出1,data2输出2。

最佳答案

使用replace()split()内联

var payload = "(64.4000015258789, 14.899999618530273)";

// remove the parentheses and split the remainder into an array
var arr = payload.replace( /[\(\)]/g, "" ).split( /\s*,\s*/ );

console.log( parseFloat( arr[ 0 ] ) );
console.log( parseFloat( arr[ 1 ] ) );

RegExp /\s*,\s*/ in split() 将在 ","", ";它处理逗号前后存在任意数量空格的可能性。
效果是生成的数组值自动为 trimmed .

OP代码错误原因

JS slice接受两个参数:

begin Optional
Zero-based index at which to begin extraction.
A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
If begin is undefined, slice begins from index 0.

end Optional
Zero-based index before which to end extraction. slice extracts up to but not including end.
For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
If end is omitted, slice extracts through the end of the sequence (arr.length).
If end is greater than the length of the sequence, slice extracts through the end of the sequence (arr.length).

var foo = "(value, value)";

console.log( foo.slice( 0, -1 ) ); // "(value, value"

console.log( foo.slice( 1, -1 ) ); // "value, value"

阅读一些文档后

我认为下面的代码可能有效。这只是基于有限检查和零经验的最佳猜测。

var arr = msg.payload.slice( 1, -1 ).split( /\s*,\s*/ );

msg.payload = { "value_name_1": arr[ 0 ], "value_name_2: arr[ 1 ] };
// or
msg.payload = arr;

return msg;

在以下2个文档中,代码示例return msg;修改了它的payload属性。

这似乎是完成的方式。

关于javascript - JS 切片、拆分和解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44754418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com