我正在嘗試制作一個矩陣類。當我把cof()函式作為一個方法使用時,它沒有作業,并顯示了這個錯誤。 practice:47 未發現的型別錯誤。無法讀取未定義的屬性'cof'。
但是當我在det()方法中作為一個函式使用它時,它可以完美地作業。誰能解釋一下為什么會發生這種情況?
class Matrix{
constructor(matrix){
this.matrix = matrix
}
cof(matrix = this.matrix, i, j) {
let cofMat = matrix.map(row =>)
row.filter((_, colIndex) =>/span> j !== colIndex)
)
cofMat.splice(cofMat[i],1)
回傳 cofMat
}
det(matrix = this.matrix) {
let validInput = true;
//input validation。
let columnLength = matrix.length;
matrix.forEach((row) =>/span>
row.length == columnLength ? (validInput = true) : (validInput = false)
);
if (!validInput) return "輸入一個有效的n*n矩陣" 。
///使用第一行確定矩陣。
//這個函式作為一個方法不能正常作業。
function cof(matrix, i, j) {
let cofMat = matrix.map(row =>
row.filter((_, colIndex) =>/span> j !== colIndex)
)
cofMat.splice(cofMat[i],1)
回傳 cofMat
}
function recursiveDeterminantMatrix(matrix) {
if (matrix.length ==2 && matrix[0] 。 length === 2) {
let result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1] [0] 。
return result。
} else {
let answer = 0;
for(let i =0; i< matrix.length; i ) {
let cofactor =
(-1) ** i *
矩陣[0][i] * *
recursiveDeterminantMatrix(this.cof( matrix, 0, i)) 。
answer = cofactor。
};
return答案。
}
}
return recursiveDeterminantMatrix(矩陣)。
}
}
let matrix = [[1,2,3], [4, 5,6],[7,8,8] 。]
let mat = new Matrix(matrix).det()
uj5u.com熱心網友回復:
當recursiveDeterminantMatrix函式執行時,this不會評估到類的實體,因為它不是一個方法,只是一個普通函式。
你可以將類的實體保存在一個self變數中,以便在內部函式中正確使用。
det(matrix =this.matrix) {
const self = this;
// ...
function recursiveDeterminantMatrix(matrix) {
if (matrix.length ==2 && matrix[0] 。 length === 2) {
let result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1] [0] 。
return result。
} else {
let answer = 0;
for(let i =0; i< matrix.length; i ) {
let cofactor =
(-1) ** i *
矩陣[0][i] * *
recursiveDeterminantMatrix(self.cof(matrix, 0, i) )。)
answer = cofactor。
};
return答案。
}
}
return recursiveDeterminantMatrix(矩陣)。
}
關于這個關鍵詞的更多資訊,請查看MDN Docs
uj5u.com熱心網友回復:
你可以使用bind來實作。
recursiveDeterminantMatrix(this. cof(matrix, 0, i).bind(this) )。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/319326.html
標籤:
下一篇:向后遞回
