交换二维数组的行列(AS3)

最近用perl做了一个项目,将N个某个目录下的N 个CSV插入到Sybase数据库中,CSV是个交叉表,在处理时需要交换二维数组的行列。用perl来实现很简单,其实用ActionScript也不难。

代码如下:

package com.riafan.utils {
  /**
   * Class that contains static utility methods for manipulating and working
   * with Arrays
   * @author Flying
   * @version 1
   * @tiptext
   */
  public class ArrayUtil {
    /**
     * Switch the rows and columns of a 2d array array
     * @param arr The 2d array whose dimensions will be switched
     * @return A new array which contains items after switch
     */
    public static function switchDimensions(arr : Array) : Array {
      var newArr : Array = new Array();
      var rowMax : uint = arr.length;
      var colMax : uint;
      try {
        if(arr[0] is Array) {
          colMax = arr[0].length;
        }else {
          throw new TypeError("muse be a 2d array");
        }
      }
      catch (error : TypeError) {
        trace(error.message);
      }
      for (var col : uint = 0; col < colMax; col++) {
        var tmpArr : Array = new Array();
        for (var row : uint = 0; row < rowMax; row++) {
          tmpArr[row] = (arr[row][col]);
        }
        newArr[col] = tmpArr;
      }
      return newArr;
    }
  }
}

说明:switchDimensions方法用来交换初始二维数组的行列,并返回新的二维数组。比如说[[1,2],[true,false],[‘A’,’B’]]将返回[[1,true,’A’],[2,false,’B’]]。

发表评论