You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何函数返回Uint8Array后原变量commandframe未变化?

为什么函数返回合并后的Uint8Array但原变量未改变?

问题场景

你执行了以下代码,调试时发现GetCRC16Full函数内的mergedArray确实是合并后的[0x01,0x00,0xff],但函数返回后commandframe并没有变化:

commandframe = new Uint8Array([0x01,0x00]); 
GetCRC16Full(commandframe, true);

function GetCRC16Full(cmd, IsHighBefore) {
    let check= [0xff];
    var mergedArray = new Uint8Array(cmd.length + check.length);
    mergedArray.set(cmd);
    mergedArray.set(check, cmd.length);
    return mergedArray;
}

原因分析

  1. 函数创建了新数组而非修改原数组
    GetCRC16Full函数里新建了一个Uint8Array实例mergedArray,并把原数组cmd和check的数据复制进去,最后返回这个新数组。整个过程中,传入的原数组cmd(也就是commandframe)没有被做任何修改。

  2. 未接收函数返回值
    你调用函数时只是执行了GetCRC16Full(commandframe, true);,但没有把函数返回的新数组赋值给commandframe,所以原变量的引用不会更新。

解决方法

把函数返回的新数组赋值给commandframe即可:

commandframe = new Uint8Array([0x01,0x00]); 
// 接收函数返回的合并后数组,更新commandframe的引用
commandframe = GetCRC16Full(commandframe, true);

注意:Uint8Array的长度是固定的,无法直接扩容原数组,所以通过返回新数组的方式是合理的。

内容的提问来源于stack exchange,提问作者Vince

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:15:42