移动一个二维数组

Javascript: shift a bidimensional array

本文关键字:一个 二维数组 移动      更新时间:2023-09-26

我以以下方式创建了一个样本数组:

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值

有更好的吗?谢谢!

可以使用Array。映射来改变数组中的每个元素,而不需要显式循环。

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,并使用第二个数组,如Circular buffer

备选答案如果

  • 一个样本是[x, y]
  • x是一个序列0,1,2,…, m(没有间隙),当您收到新样品时,您将:
然后

// 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是数组的索引。


性能方面,我不会改变源数组,但访问器函数。

所以你可以有一个类在读取时提供移位,例如 shiftearray类,其中通道是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]

以上只是概念代码,未经过测试,您应该添加边界检查