Javascript矩阵行列式

时间:2013-05-11 09:29:01

标签: javascript html matrix

矩阵行列式函数不起作用,我不知道为什么。对我来说似乎没问题。有人可以帮助我。

HTML

<div id = "table1">
            <div class = "header">Wyznacznik [2x2]</div>
                <form id = "row1">
                    <input type = "text" class = "det1"/><!--first row-->
                    <input type = "text" class = "det1"/>
                </form>
                <form id = "row2">
                    <input type = "text" class = "det1"/><!-- second row-->
                    <input type = "text" class = "det1"/>
                </form>
            <div class = "count"><a href = "#" onclick="det('det1','caclValue2')">Wylicz</a></div>
                <input type = "text" id = "calcValue2"/>
            </div>

的javascript

function det(className,outputId){
var arr = document.getElementsByClassName(className);
var determinant = 0; 
if(arr.length == 2){
determinant = (arr[0].value*arr[3].value) - (arr[1].value*arr[2].value);
}
else if(arr.length == 3){
determinant = (arr[0].value*((arr[4].value*arr[8].value) - (arr[5].value *     arr[7].value))) - 
(arr[1].value*((arr[3].value*arr[8].value) - (arr[5].value * arr[6].value))) +
(arr[2].value*((arr[3].value*arr[7].value) - (arr[4].value * arr[6].value))); 
}
document.getElementById(outputId).value = determinant;
return determinant;
}

编辑!:如果语句应该有arr.length == 4,否则如果arr.length == 9。

1 个答案:

答案 0 :(得分:0)

您将数组的长度过滤为2,但之后您尝试访问超出该数组的索引:

if(arr.length == 2){
    determinant = (arr[0].value*arr[3].value) - (arr[1].value*arr[2].value);
}

其他if语句也是如此。你真的看过控制台中的错误吗?