我写了这个方法来转置一个 javascript 数组
Array.prototype.transpose = function () {
let rows = this.length;
let cols = this[0].length;
let ret = [[]];
for (y=0;y<cols;y++)
for (x=0;x<rows;x++)
ret[y][x]=this[x][y]
return ret;
}
但是,这是非常低效的,因为它实际上复制了整个数据。
我更喜欢做的是使用标志 transposed?
将 arr[x][y]
视为 arr[y][x]
如果它打开了。
然后,函数 transpose
会切换它。
这如何在 javascript 中完成?
最佳答案
替代方法可能是使用 proxies .它们允许您捕获对象成员访问(例如数组括号引用)并返回自定义值。
这是一个简单的实现,只支持 get
访问索引和 length
属性,但不支持其他任何东西。如果你真的想要,你可以扩展它以支持迭代、枚举、设置、数组方法(如 join
、map
, ...),...等,但如果你走那么远,真的会使用这些方法,那么问题就变成了是否值得所有的努力,因为如果你像你那样做,总体性能可能会更好:将数组复制到它的转置对应部分。
无论如何,这里是:
var a = [ [1,2,3],
[4,5,6] ];
a.transposed = new Proxy(a, {
get: (arr, col) =>
+col >= 0 ? new Proxy({ length: a.length }, {
get: (obj, row) => +row >=0 ? arr[row][col] : obj[row]
})
: col == 'length' ? arr[0] && arr[0].length
: col == 'original' ? arr
: undefined
});
var t = a.transposed;
// Mutate a, to demo that also t shows the mutation:
a[0][2] = 3.5;
console.log('a = ', JSON.stringify(a));
console.log('a[0][2] = ', a[0][2], ', t[2][0] = ', t[2][0]);
console.log('a[0].length = ', a[0].length, ', t.length = ', t.length);
console.log('a.length = ', a.length, ', t[0].length = ', t[0].length);
// you can revert back to original array from the transposed one:
console.log('a === t.original?', a === t.original);
关于javascript - 有效地转置javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40380219/