[英]Changing the Array Prototype in JavaScript
I'm trying to change the Array Prototype and access columns as if they are rows therefor doing a custom matrix transposition. 我正在尝试更改数组原型和访问列,就好像它们是用于自定义矩阵转置的行一样。 I want to make sure that the access of each column doesn't require re-allocating and creating an entirely new object just to access a particular column. 我想确保对每一列的访问都不需要重新分配和创建一个全新的对象来访问特定的列。
For example... 例如...
var mcol = new column([[0,1,2],[3,4,5],[6,7,8]]);
alert(mcol[1]);
What I'm looking for is to read the column as if it was a row... (doing a 90 degree transform on the matrix) 我正在寻找的是将列读为好像是一行...(在矩阵上进行90度变换)
mcol[1] = [1,4,7];
Any suggestions? 有什么建议么?
You can use this constructor: 您可以使用以下构造函数:
function column() {
var arr = Array.prototype.slice.call(arguments);
return arr;
}
Allowing you to do what you want. 允许您做自己想做的事。
var mcol = new column([0,1,2], [3,4,5], [6,7,8]);
alert(mcol[1]); // alerts [3, 4, 5]
I'd suggest you make a Matrix
constructor with a column
method: 我建议您使用column
方法创建Matrix
构造函数:
function Matrix() {
this._rows = Array.prototype.slice.call(arguments);
}
Matrix.prototype.column = function (i) {
// See (1)
return this._rows.map(function (row) {
return row[i];
});
};
var m = new Matrix([0,1,2],[3,4,5],[6,7,8]);
console.log(m.column(1)); // [1,4,7]
(1) https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map (1) https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
The solution I have is a work around and involves copying the array to a new array which I don't like. 我的解决方案是一种解决方法,涉及将阵列复制到我不喜欢的新阵列中。 It does override the Array prototype. 它的确覆盖了Array原型。
Array.prototype.rotate = function () {
var rotated = [];
var columns = 1;
for(var col = 0; col < columns; col++) {
var myrow = [];
for(var row = 0; row < this.length; row++){ // this.length is the longest column
if(this[row].length > columns){
columns = this[row].length;
}
if(this[row].length > col){
myrow.push(this[row][col]);
} else {
myrow.push(null);
}
}
rotated.push(myrow);
}
return rotated;
}
var mcol = [[0,1,2], [3,4,5], [6,7,8]];
mcol = mcol.rotate();
alert(mcol[1]);
Alerts [1,4,7] 警报[1,4,7]
Does anyone know of a solution that doesn't require someone to copy the entire array to a new array? 有人知道不需要别人将整个阵列复制到新阵列的解决方案吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.