【问题标题】:Display variable and array显示变量和数组
【发布时间】:2019-09-09 10:35:57
【问题描述】:

伙计们,我有一个问题。

我有一个应用程序,我在其中使用 BLE 从外部设备注册数据。

我有一个“时间”和一个用于“加速度”的数组。

const time = parseInt(
          Buffer.from(characteristic.value, "base64")
            .readUInt16LE(0)
            .toString(16),
          16
        );
        const acc_dx = [2, 4, 6].map(index => {
          const hex = Buffer.from(characteristic.value, "base64")
            .readInt16LE(index)
            .toString(16);
          return Number.parseInt(hex, 16);
        });
        const accUpdate_acc_dx = [...this.state.array_acc_dx, this.state.time, this.state.acc_dx]
        this.setState({ array_acc_dx: accUpdate_acc_dx })

array_acc_dx 的结果如下:

[1520,[42,-419,-926],1520,[41,-420,-927],1520,[41,-421,-927],1520,[41,-421,-926 ],1580,[40,-420,-927],1640,[40,-420,-926],1640,[41,-420,-926],1640,[41,-419,-926]

我会得到这个:

1520: [42,-419,-926],

1520: [41,-420,-927],

1520: [41,-421,-927],

1580: [40,-420,-927],

我该怎么做才能拥有这种数组?

【问题讨论】:

  • 离题:parseInt( someNumber.toString(16), 16); 的意义何在?
  • @Thomas 将数字转换为字符串
  • @Jack23 但someNumber.toString(16) 会将十六进制数字作为字符串返回...然后执行parseInt(str, 16) 将再次将该十六进制值转换为数字。如果readUInt16LE 返回一个数字,那么您不需要双重转换即可获得相同的数字。如果没有,我认为不需要双重转换。
  • @VLAZ 现在我正在尝试你所说的:)
  • according to the docs, readInt16LE 返回一个与MDN Number type相关的整数。

标签: javascript react-native


【解决方案1】:

我已经清理了您代码中的一些位,但我假设以下代码可以满足您的要求。

  • 我认为没有必要为要读取的每个索引使用单独的缓冲区。

  • 我已经提到了将数字转换为十六进制的部分,只是为了立即将其解析回数字;那是无用的代码。

  • 您可以一次性解析timeacc_dx 的值。无需重复代码。

  • 根据之前的状态更新状态时,使用this.setState(previousState => newState)

const buf = Buffer.from(characteristic.value, "base64");
const [time, ...acc_dx] = [0,2,4,6].map(index => buf.readInt16LE(index));

this.setState(state => ({
  time,
  acc_dx,
  array_acc_dx: [
    ...state.array_acc_dx, 
    [time, acc_dx]
  ]
}));

【讨论】:

  • 你能帮我看看这段代码的一部分吗?谢谢
  • @Jack23 当然,有什么问题/疑问?
  • 我对另一个变量也有类似的问题: const [time, ...pressure ] = [0, 2, 4, 6, 8].map(index => buf.readUInt16LE(index) );但问题是压力接受如下数据:P1(2 字节)、P2(2 字节)、P3(2 字节)、P4(2 字节)、P5(2 字节)。所以我不能插入时间。你知道我该怎么做吗?
  • @Jack23 在这种情况下是没有 int16LE 的时间,就像在这个问题中一样?然后分别解析timepressure。我将timeacc_dx 组合在一起,因为它们全部计算为buf.readInt16LE(index)
  • 那么我可以像我的帖子那样使用时间吗?那我怎么才能把它和压力结合起来呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多