在2D数组中移动行和列-Javascript [英] Shifting rows and columns in 2D arrays - Javascript

查看:115
本文介绍了在2D数组中移动行和列-Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的情况:

var array = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]

我正在尝试创建一个可移动行或列的函数,因此结果将是:

And I am trying to create a function that shifts either a row or a column so the result would be:

shiftRow(array, 1) 

[
  [3,1,2],
  [4,5,6],
  [7,8,9]
]

shiftColumn(array,1)

[
  [7,2,3],
  [1,5,6],
  [4,8,9]
]

我希望第一个数字是最后一个数字,然后在任何情况下都从那里继续。我已经尝试了几个嵌套的for循环,但是我非常想解决这个问题。请记住,尽管我只编码了几个月。

I want the first number to be the last number then continue from there in any instance. I have tried several nested for loops, and I'm quite stuck at figuring this out. Keep in mind I have only been coding for a few months though.

这是我到目前为止所拥有的。最后,它给了我一个 undefined 错误,并且它以错误的方式移动。

This is what I have so far. It gives me an undefined error at the end and it is moving it the wrong way.

function shiftRow(arr) {
  var temp = arr
  for(var i = 0; i < temp.length; i++) {
    for(var j = 0; j < temp[i].length; j++) {
      temp[i][j] = temp[i][j+1]
    }
  }
  return temp;
}


推荐答案

以前的答案看起来还可以,但是在处理数组索引时缺少一件 major 东西;验证检查。

The previous answers looks ok, but lacks one major thing when dealing with array indexes ; validation checks.

您不想尝试访问不存在的数组索引。因此,我创建了一个小类来根据需要对数组进行验证。如果行或列索引无效,这将引发错误

You do not want to try to access non-existent array indexes. Therefore, I created a small class to shift your array as needed, with validation. This will throw an Error if either the row or column index is invalid.

class ArrayShifter {
    static showArray(array) {
        // console.log("Array : ", array);
        console.log('------');
        for (const [index, elem] of array.entries()) {
            console.log(''+elem);
        }
    }

    static validateRowIndex(array, rowIndex) {
        if (!isArray(array) || !isInt(rowIndex) || rowIndex <= 0 || rowIndex > array.length) {
            throw new Error('The row index is wrong');
        }
    }

    static validateColumnIndex(array, columnIndex) {
        if (!isArray(array) || !isInt(columnIndex) || columnIndex <= 0 || columnIndex > array[0].length) {
            throw new Error('The column index is wrong');
        }
    }

    static shiftRow(array, rowIndex) {
        ArrayShifter.validateRowIndex(array, rowIndex);
        array[rowIndex - 1].unshift(array[rowIndex - 1].pop());

        return array;
    }

    static shiftColumn(array, columnIndex) {
        ArrayShifter.validateColumnIndex(array, columnIndex);
        let prev = array[array.length - 1][columnIndex - 1];

        for (const elem of array) {
            let tmp = elem[columnIndex - 1];
            elem[columnIndex - 1] = prev;
            prev = tmp;
        }

        return array;
    }
}

let sourceArray1 = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
];
let sourceArray2 = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
];
let controlArrayShiftRow = [
    [3,1,2],
    [4,5,6],
    [7,8,9],
];
let controlArrayColumnRow = [
    [7,2,3],
    [1,5,6],
    [4,8,9],
];

// arrayShifter.showArray(sourceArray1);
console.log(`Shift row test is ${areArraysEqual(controlArrayShiftRow, ArrayShifter.shiftRow(sourceArray1, 1))}.`);

// arrayShifter.showArray(sourceArray2);
console.log(`Shift column test is ${areArraysEqual(controlArrayColumnRow, ArrayShifter.shiftColumn(sourceArray2, 1))}.`);




//-------------------- Unimportant js functions --------------------
function isArray(arr) {
    if (Object.prototype.toString.call([]) === '[object Array]') { //Make sure an array has a class attribute of [object Array]
        //Test passed, now check if is an Array
        return Array.isArray(arr) || (typeof arr === 'object' && Object.prototype.toString.call(arr) === '[object Array]');
    }
    else {
        throw new Exception('toString message changed for Object Array'); //Make sure the 'toString' output won't change in the futur (cf. http://stackoverflow.com/a/8365215)
    }
}
function isInt(n) {
    return typeof n === 'number' && parseFloat(n) === parseInt(n, 10) && !isNaN(n);
}
function areArraysEqual(a1, a2) {
    return JSON.stringify(a1) == JSON.stringify(a2);
}

工作代码可以在 codepen

这篇关于在2D数组中移动行和列-Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆