首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试返回矩阵中的列,但未定义具有正确控制台输出的方法

尝试返回矩阵中的列,但未定义具有正确控制台输出的方法
EN

Stack Overflow用户
提问于 2018-12-18 03:31:54
回答 1查看 106关注 0票数 0

所以,我花了一些时间来做这个难题,我终于让我的控制台输出正确了。我刚开始使用JavaScript方法,我很难弄清楚为什么this.columnsundefined

下面是我的代码:

代码语言:javascript
复制
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])
        })
    });
}

我尝试通过的特定测试用例如下:

代码语言:javascript
复制
  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分隔的字符串。这会让你深入了解为什么我会有这样的代码。

这是我的控制台输出。

代码语言:javascript
复制
 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

这是一个明显的范围问题,但我完全忽略了它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-18 03:46:39

您可能希望使用reduce()来构建列的数组。对行执行map()并不能真正起作用,因为列数可能与行数不同。

对于每一行,您将遍历数字,并使用forEach中的索引将数字添加到适当的列。

类似于:

代码语言:javascript
复制
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)

如果您不想一次计算所有列,也可以创建一个简单的函数来获取特定的列:

代码语言:javascript
复制
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))

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53821869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档