Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

javascript - Javascript函数返回数组,但仅返回最后一个数组(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.(我尝试制作一个JavaScript函数来显示使用高斯方法求解线性方程组的步骤 。)

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.(我得到的是window.GaussMatrixSteps是相同矩阵的数组(最后一步),而不是来自不同步骤的不同矩阵。) Is it really how JavaScript works?(这真的是JavaScript的工作方式吗?)   ask by aryafilan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(您还需要养成使用letconst声明所有变量的习惯,并避免将window对象用作变量占位符。) 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循环变量,如下所示:) for (let i = 0; i < n; i++) { for (let k = i + 1; k < n; k++) { for (let j = 0; j <= n; j++) { } } }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...