gpt4 book ai didi

javascript - array.concat() 的问题

转载 作者:行者123 更新时间:2023-11-29 17:36:12 27 4
gpt4 key购买 nike

我正在尝试使用递归调用来连接返回数组

这个问题的方向是:接收到数据流,需要将其反转。

每段长度为8位,意味着这些段的顺序需要颠倒,例如:

11111111 00000000 00001111 10101010 (byte1) (byte2) (byte3) (byte4)应该变成:

10101010 00001111 00000000 11111111 (byte4) (byte3) (byte2) (byte1)总位数总是 8 的倍数。

尝试不同的事物组合真的...

function dataReverse(data) {
//split incoming array into array values consisting of 8 numbers each.
//var octGroups = data.length / 8;
var result = [];
//recursive call
function shuffler(array){
let input = array;
//base case
if(input.length === 0){
return result;
} else {
//concat result with 8 values at a time
let cache = input.splice(-8,8);
result.concat(cache);
return shuffler(input);
}
return result;
}





var reversed = shuffler(data);
//base case is if data.length === 0 return result else
//reverse iterate through array, concating to new return array
//return result
return reversed;
}

console.log(dataReverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]));

预计会反转输入数组,从末尾开始一次连接一个包含 8 个值的结果数组,但不会反转数字的顺序。

我上面的尝试返回了一个零长度数组。我做错了什么?

最佳答案

使用join代替concat

function dataReverse(data) {
//split incoming array into array values consisting of 8 numbers each.
//var octGroups = data.length / 8;
var result = [];
//recursive call
function shuffler(array) {
let input = array;
//base case
if (input.length === 0) {
return result;
} else {
//concat result with 8 values at a time
let cache = input.splice(-8, 8);
result.push(cache.join(''));
return shuffler(input);
}
return result;
}


var reversed = shuffler(data);
//base case is if data.length === 0 return result else
//reverse iterate through array, concating to new return array
//return result
return reversed;
}

console.log(dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));

关于javascript - array.concat() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56403647/

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