所以,我花了一些时间来做这个难题,我终于让我的控制台输出正确了。我刚开始使用JavaScript方法,我很难弄清楚为什么this.columns
是undefined
。
下面是我的代码:
export var Matrix = function(matrix) {
var self = this
let splitMatrix = matrix.split("\n")
self.rows = splitMatrix.map(function(row){return row.split(" ").map( Number )})
self.columns = self.rows[0].forEach(function(index){
self.rows.map(function(column){
console.log(column[index])
})
});
}
我尝试通过的特定测试用例如下:
test('can extract column from non-square matrix', () => {
expect(new Matrix('1 2 3\n4 5 6\n7 8 9\n8 7 6').columns[2]).toEqual([3, 6, 9, 6]);
});
矩阵是由\n
分隔的字符串。这会让你深入了解为什么我会有这样的代码。
这是我的控制台输出。
console.log matrix.js:7
1
console.log matrix.js:7
4
console.log matrix.js:7
7
console.log matrix.js:7
8
console.log matrix.js:7
2
console.log matrix.js:7
5
console.log matrix.js:7
8
console.log matrix.js:7
7
console.log matrix.js:7
3
console.log matrix.js:7
6
console.log matrix.js:7
9
console.log matrix.js:7
6
一切都很好..。除了一个事实:self.columns === undefined
这是一个明显的范围问题,但我完全忽略了它。
发布于 2018-12-18 03:46:39
您可能希望使用reduce()
来构建列的数组。对行执行map()
并不能真正起作用,因为列数可能与行数不同。
对于每一行,您将遍历数字,并使用forEach
中的索引将数字添加到适当的列。
类似于:
var Matrix = function(matrix) {
let splitMatrix = matrix.split("\n")
this.rows = splitMatrix.map(row => row.split(" ").map( Number ))
this.columns = this.rows.reduce((arr, row) => {
row.forEach((n, i) => {
if (!arr[i]) arr[i] = [] // if there's no entry yet for column i, make it
arr[i].push(n) // push to the column
})
return arr
}, []);
}
console.log(new Matrix('1 2 3\n4 5 6\n7 8 9\n8 7 6').columns)
如果您不想一次计算所有列,也可以创建一个简单的函数来获取特定的列:
var Matrix = function(matrix) {
let splitMatrix = matrix.split("\n")
this.rows = splitMatrix.map(row => row.split(" ").map( Number ))
}
Matrix.prototype.getColumn = function (colNum){
// will return undefined if no value in column
return this.rows.map(r => r[colNum])
}
let M = new Matrix('1 2 3\n4 5 6\n7 8 9\n8 7 6')
console.log(M.getColumn(1))
https://stackoverflow.com/questions/53821869
复制相似问题