[英]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.