开发者问题收集

为什么 Firebug 告诉我 JavaScript 数组未定义?

2009-03-25
2255

刚刚开始研究 JavaScript 中的基本网格分析算法,但是我遇到了一个令我困惑的错误。

var max = 9;
var testArray = new Array(
  ['7', '3', '9', '6', '4', '1', '5', '2', '8'],
  ['1', '8', '2', '7', '5', '3', '4', '6', '9'],
  ['9', '5', '7', '3', '8', '2', '1', '4', '6'],
  ['3', '1', '4', '9', '6', '7', '2', '8', '5'],
  ['6', '2', '8', '5', '1', '4', '9', '3', '7'],
  ['5', '4', '6', '2', '9', '8', '3', '7', '1'],
  ['8', '7', '1', '4', '3', '5', '6', '9', '2'],
  ['2', '9', '3', '1', '7', '6', '8', '5', '4']
);

function checkYoSelf(myGrid) {
  var i; var j;
  var horizLine = new String;
  for( i = 0; i <= (max - 1); i++ ) {
    for( j = 0; j <= (max - 1); j++) {
      document.write(i+"<br />");
      horizLine += myGrid[i][j];
    }
    var test = RegExp(i, "ig");
    var result = new Array(horizLine.match(test));
    if( result.length > 1 ) {
      alert("fail");
    }    
  }
}

html file has <a href='#' onclick="checkYoSelf(testArray);">check</a>

根据 firebug, myGrid[i] 未定义,但是我不确定为什么会这样。

我做错了什么?

3个回答

嗯,这对我有用...我刚刚将您的“max”变量替换为更动态的变量:

<script type="text/javascript">
    var testArray = new Array(
        ['7', '3', '9', '6', '4', '1', '5', '2', '8'],
        ['1', '8', '2', '7', '5', '3', '4', '6', '9'],
        ['9', '5', '7', '3', '8', '2', '1', '4', '6'],
        ['3', '1', '4', '9', '6', '7', '2', '8', '5'],
        ['6', '2', '8', '5', '1', '4', '9', '3', '7'],
        ['5', '4', '6', '2', '9', '8', '3', '7', '1'],
        ['8', '7', '1', '4', '3', '5', '6', '9', '2'],
        ['2', '9', '3', '1', '7', '6', '8', '5', '4']
    );

    function checkYoSelf(myGrid) {
        var i;
        var j;
        var horizLine = new String;

        var maxRows = myGrid.length;
        for( i = 0; i < maxRows; i++ ) {
            var maxColumns = myGrid[i].length;
            for( j = 0; j < maxColumns; j++) {
                document.write(i+"<br />");
                horizLine += myGrid[i][j];
            }

            var test = RegExp(i, "ig");
            var result = new Array(horizLine.match(test));
            if( result.length > 1 ) {
                alert("fail");
            }
        }
    }
</script>

<a href='#' onclick="checkYoSelf(testArray);">check</a>

不确定您想用它做什么,但至少它没有给出任何错误。

Seb
2009-03-25

max 来自哪里?

max is defined globally (in this case max = 9)

你只有 8 行。

nickf
2009-03-25

从您对Nickf的评论中的答案:这是因为Max是9,但是您的数组中只有8行。

chaos
2009-03-25