簡體   English   中英

從其他二維數組 Javascript 的部分創建二維數組

[英]Creating 2d array from section of other 2d array Javascript

我正在嘗試剪切由x, yw, h指定的二維數組的一部分。 我試圖切割的數組的一個例子是


var arr = [
            ['0', '1', 'd', 'a', '1', '1'],
            ['0', 's', '0', 'f', 's', 'g'],
            ['b', 'x', 'e', '0', 'v', 'a'],
            ['a', 'e', 'n', '0', 'z', 'm'],
            ['b', 'x', 'e', '0', 'v', 'a'],
         ];

所以如果我調用snapshot(2, 1, 4, 2)我想要的 output 將是

var retarr = [
                 ['0', 'f', 's', 'g'],
                 ['e', '0', 'v', 'a'],
             ]

到目前為止,我可以切割部分並成功返回一個新數組,但前提是我的W idth 和H八相等。

snapshot(x, y, w, h){
    var retgrid = new Grid(w, h); 
    var startX = x;
    var startY = y;
    var endX = x + w;
    var endY = y + h;
    console.log(`x: ${x} y: ${y}`)
    console.log(`w: ${w} h: ${h}`)

    for(var i = startY; i < endY; i++){
        for(var j = startX; j < endX; j++){
           // console.log(retgrid)
            retgrid[j - startX][i - startY] = this.grid[j][i]
        }
    }
    console.log(retgrid)
    return retgrid;
}

不斷發生的錯誤是game.js:316 Uncaught TypeError: Cannot set property '-1' of undefined

我已經有一段時間了。 我知道這可能只是一些簡單的邏輯錯誤,但由於某種原因,我無法確定它。 誰能發現我做錯了什么?

使用.slice可以提取 arrays 的位。 首先拉出 Y -> Y + H 處的行。接下來,使用 map() 到 go 穿過每個行,將每個行切成 X -> X + W 的列。

您需要添加安全防護裝置以避免超出 arrays 的尺寸或形狀。

 var arr = [ ['0', '1', 'd', 'a', '1', '1'], ['0', 's', '0', 'f', 's', 'g'], ['b', 'x', 'e', '0', 'v', 'a'], ['a', 'e', 'n', '0', 'z', 'm'], ['b', 'x', 'e', '0', 'v', 'a'], ]; console.log(snapshot(2, 1, 4, 2)); function snapshot(x, y, w, h) { return arr.slice(y, y + h).map(a => a.slice(x, x + w)) }

通過將其分為兩個步驟,可以大大簡化此任務:

第 1 步:提取所需的完整行

第 2 步:從提取的行中提取所需的列。

 const arr = [ ['0', '1', 'd', 'a', '1', '1'], ['0', 's', '0', 'f', 's', 'g'], ['b', 'x', 'e', '0', 'v', 'a'], ['a', 'e', 'n', '0', 'z', 'm'], ['b', 'x', 'e', '0', 'v', 'a'], ]; function snapshot (array, colStart, rowStart, cols, rows) { // slice out the rows const fullRows = array.slice(rowStart, rowStart+rows); console.log('fullRows:', fullRows); // cut down the rows const cutRows = fullRows.map(row => row.slice(colStart, colStart+cols)); return cutRows; } const result = snapshot(arr, 2, 1, 4, 2); console.log('result:', result);

首先filter掉不需要的行並使用mapslice

 const snapshot = (arr, x, y, w, h) => arr.filter((_, i) => i >= y && i < y + h).map((items) => items.slice(x, x + w)); var arr = [ ["0", "1", "d", "a", "1", "1"], ["0", "s", "0", "f", "s", "g"], ["b", "x", "e", "0", "v", "a"], ["a", "e", "n", "0", "z", "m"], ["b", "x", "e", "0", "v", "a"], ]; console.log(snapshot(arr, 2, 1, 4, 2));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM