[英]Javascript: shift a bidimensional array
我通过以下方式创建了一个样本数组:
var data = new Array(8);
...
data[n].push([x, y]);
其中n是通道(0-7),[x,y]所选通道的当前样本。 对于特定的应用程序,每当我获得一个新样本时,我都需要保持x值不变(0、1、2、3,... m)并移动y值。
一个简单的m = 3的例子。第一次加载后,我得到:
data[0] -> [0, 2] [1, 4] [2, 6]
当收到一个新样本时,我想像这样更改数组:
data[0] -> [0, 4] [1, 6] [2, 8]
因为m的值可能高达5000,所以我想知道哪种方法是最好的方法。 当然,我可以循环整个数组,将位置j的y值更改为位置j + 1的y值。
有更好的东西吗? 谢谢!
提供替代答案
然后
// push the value of the sample, not X, just Y
data[0].push(value)
// remove the first element from the array.
data[0].shift()
x是数组的索引。
在性能方面,我不会更改源数组,而是会更改访问器函数。
因此,您可以拥有一个在读取时提供移位的类,例如ShiftedArray类 ,其中channel是data [z] :
var shifter = 0
function get(index) {
return [channel[index][0], channel[index + this.shifter][1]];
}
那么您可以提供增加班次:
function increase() {
this.shifter++;
}
或减少它:
function increase() {
this.shifter--;
}
然后访问数组数据:
var item1 = shiftedArray.get(0);
// shall return [0, 2]
shiftedArray.increase();
var item2 = shiftedArray.get(0);
// shall return [0, 4]
以上只是概念代码,未经测试,应添加边界检查。
您可以使用Array.map更改数组中的每个项目,而无需显式循环。
var data = [
[0,2], [1,4], [2,6]
];
function update(data) {
data.map(function(item,key) {
if(key+1>data.length-1) return;
data[key][1] = data[key+1][1];
});
// if we shift, the last item Y should have empty value
data[data.length-1][1] = undefined;
}
update(data);
console.log(data); // [0,4], [1,6], [2,undefined]
见小提琴 。
您可能还喜欢这种受@rab解决方案启发的黑魔法。
var data = [ [0,2], [1,4], [2,6] ];
data.map(function(_,i,o){o[i][1]=o[++i]&&o[i][1]});
console.log(data); // [0,4], [1,6], [2,undefined]
尝试在两个单独的数组上拆分data
,并使用第二个数组,例如圆形缓冲区 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.