我正在尝试使用递归调用来连接返回数组
解决此问题的方法是:
接收到数据流,需要将其反转。
每个段的长度为8位,这意味着这些段的顺序需要颠倒,例如:
11111111 00000000 00001111 10101010
(字节1)(字节2)(字节3)(字节4)
应该变成:
10101010 00001111 00000000 11111111
(字节4)(字节3)(字节2)(字节1)
总位数始终是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个值,但不会反转数字的顺序。
我在上面的尝试返回了一个零长度的数组。我做错了什么?
最佳答案
concat返回一个新数组,您需要将其分配回结果
result = result.concat(cache);
如果您希望每个字节为8个字符的字符串,则可以使用join
result = result.concat(cache.join(''));
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 = 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字节的组,然后反转,然后缩减为单个数组
let dataReverse = (data) => {
let count = 0
let temp = []
let group = data.reduce((op, inp) => {
temp.push(inp)
if (count === 8) {
op.push(temp)
temp = []
}
return op
}, [])
if (temp.length) group.push(temp)
return group.reverse().reduce((op,inp)=>op.concat(inp))
}
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]));