gpt4 book ai didi

javascript - JavaScript 中二维数组未正确填充且未定义

转载 作者:行者123 更新时间:2023-12-02 17:29:25 25 4
gpt4 key购买 nike

我正在编写一个具有两个子函数的函数:一个用于从表单中的两个值打印二维数组,另一个用于打印二维数组。此时,我一直在尝试使用具有整数值的变量来填充二维数组,但它们没有被正确填充。函数中 min 变量的值似乎为 0,而不是传递的值。

无论如何,在创建 2D 数组之后,我尝试测试打印 2D 数组“twoDarray”,但它显示为未定义?

        function isValid(frm) {
var xValue = document.getElementById("X").value;
var yValue = document.getElementById("Y").value;
if (xValue <= yValue)
{
/* Draw out the multiplication table. */
function gen2Darray(min, max)
{
var lengthOf2Darray = (max - min);
var twoDarray = new Array(lengthOf2Darray);
for (var i = 0; i < lengthOf2Darray; i++)
{
twoDarray[i] = new Array(lengthOf2Darray);
for (var j = 0; j < lengthOf2Darray; j++)
{
twoDarray[i][j] = ((min + i) * (min + j)); // only takes i
}
}
}
gen2Darray(xValue, yValue);

function print_2d_string_array (array)
{
// print twoDarray, but twoDarray undefined here
}

我已经创建了一个 jsfiddle 帐户,但它在网站上的工作方式不同:http://jsfiddle.net/imparante/5yTEv/ .

修复:

function isValid(frm) {
var xValue = document.getElementById("X").value;
var yValue = document.getElementById("Y").value;
var lengthOf2Darray = (yValue - xValue);
var twoDarray = new Array(lengthOf2Darray);

if (xValue <= yValue) {
/* Draw out the multiplication table. */
function gen2Darray(min, max) {
// var lengthOf2Darray = (max - min);
// var twoDarray = new Array(lengthOf2Darray);
for (var i = 0; i < lengthOf2Darray; i++) {
twoDarray[i] = new Array(lengthOf2Darray);
for (var j = 0; j < lengthOf2Darray; j++) {
twoDarray[i][j] = ((min + i) * (min + j));
$("#table").append(twoDarray[i][j] + " ");
}
}
return twoDarray;
}
gen2Darray(xValue, yValue);

function print_2d_string_array(array){
// print twoDarray
}

最佳答案

您在 twoDarray 上未定义,因为该数组是在 gen2Darray() 内声明和创建的,但您试图从 print_2d_string_array()< 访问它.

如果将 vartwoDarray = new Array(); 移至 xValueyValue 声明,应该可以解决未定义的错误。

Bin example

function isValid(frm) {
var xValue = document.getElementById("X").value;
var yValue = document.getElementById("Y").value;
var lengthOf2Darray;
var twoDarray = [];

if (xValue <= yValue){
/* Draw out the multiplication table. */
gen2Darray(xValue, yValue);
print_2d_string_array(twoDarray);
}

function gen2Darray(min, max){
lengthOf2Darray = (max - min);
twoDarray = [lengthOf2Darray];
for (var i = 0; i < lengthOf2Darray; i++){
twoDarray[i] = new Array(lengthOf2Darray);
for (var j = 0; j < lengthOf2Darray; j++){
twoDarray[i][j] = ((min + i) * (min + j)); // only takes i
}
}
}

function print_2d_string_array(array){
console.log(array);
}
}

关于javascript - JavaScript 中二维数组未正确填充且未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23206248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com