简体   繁体   中英

Javascript function returning array but only the last array

I try to make a JavaScript function to show steps of solving a Linear Equation System using the Gauss method. What I got so far (only small part of Gauss elimination method, constructing leading zeros):

let mt = [[2, 3, -1, 5], [4, 0, -3, 3], [-2, 3, -1, 1]];
gaussMethod(mt);

function gaussMethod(mtx) {
    window.GaussMatrixSteps = [];
    window.GaussMatrixSteps[0] = mtx;
    let n = mtx.length;

    for (i = 0; i < n; i++) {
        for (k = i + 1; k < n; k++) {
            var multiplier = mtx[k][i] / mtx[i][i];
            for (j = 0; j <= n; j++) {
                mtx[k][j] = mtx[k][j] - mtx[i][j] * multiplier;
            }
        }
        window.GaussMatrixSteps[i + 1] = mtx;
    }
}

What I get, window.GaussMatrixSteps is an array of same matrices (the last step) instead of different matrices from the different steps. Is it really how JavaScript works?

Your issue is that you're setting an array to the first element of another array.

let mt = [[2, 3, -1, 5], [4, 0, -3, 3], [-2, 3, -1, 1]];
gaussMethod(mt);

function gaussMethod(mtx) {
    window.GaussMatrixSteps = [];
    window.GaussMatrixSteps[0] = mtx;  // issue is here
    let n = mtx.length;

You're creating this

    [0] = [[2, 3, -1, 5], [4, 0, -3, 3], [-2, 3, -1, 1]]
    [1] = null

What you need to do is remove the reference to the first array or just reuse that array.


You also need to get into the habit of declaring all of your variables using let or const and avoid using the window object as a variable placeholder. So, you can use a private variable inside your function and return it like this:

const GaussMatrixSteps = gaussMethod(mt);

function gaussMethod(mtx) {
    const GaussMatrixSteps = [];
    GaussMatrixSteps[0] = mtx;
    ... CODE HERE
    return GaussMatrixSteps;
}

Also, don't forget to declare the inner for loop variables like this:

    for (let i = 0; i < n; i++) {
        for (let k = i + 1; k < n; k++) {
            for (let j = 0; j <= n; j++) {
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM