对数组感到困惑

时间:2020-05-26 15:31:18

标签: javascript arrays

我是lua的新JavaScript开发人员,对数组有些困惑。我正在尝试构建一个简单的2d数组,但是在初始化之后,我不断收到一个错误消息,指出该数组是“未定义的”

这是代码:

    var board = [];
    
    function initBoard(){
    	for (var i = 0; i < 8; i++){
    		board.push([]);
    		for (var j = 0 ;i < 8; i++){
    			board[j].push([]);
    		}
    	}
    }
    
    function checkSquare(x, y){
    	if (typeof(board[x][y]) === ""){
    		return false;
    	} else {
    		return true;
    	}
    }
    initBoard();
    console.log(checkSquare(3, 3));

这是错误:无法读取未定义的属性“ 3”

3 个答案:

答案 0 :(得分:1)

您不仅需要查看循环,还需要检查数组项的值。与typeof带有空字符串的结果的比较始终为false,因为Javascript中没有数据类型为空字符串。

要比较该值,可以直接用Identity/strict equality operator ===来检查该值。这将检查左侧和右侧的类型以及其值。对于对象,它将检查对象是否具有相同的引用。

function initBoard() {
  var board = [];
  for (var i = 0; i < 8; i++) {
    board.push([]);
    for (var j = 0; j < 8; j++) {
      board[i].push('');
    }
  }
  return board;
}

function checkSquare(x, y) {
  if (board[x][y] === '') { // check if the item is an empty string
    return false;
  } else {
    return true;
  }
}

var board = initBoard();

console.log(checkSquare(3, 3));

答案 1 :(得分:0)

在初始化时,您犯了一些错误。您将ji放在一起了。试试这个:

var board = [];

function initBoard(){
    for (var i = 0; i < 8; i++){
        board.push([]);
        for (var j = 0 ;j< i; j++){ //There was a mistake here
            board[j].push([]);
        }
    }
}

function checkSquare(x, y){
    if (typeof(board[x][y]) === ""){
        return false;
    } else {
        return true;
    }
}
initBoard();
console.log(checkSquare(3, 3));

var board = [];

function initBoard(){
    for (var i = 0; i < 8; i++){
        board.push([]);
        for (var j = 0 ;j< i; j++){
            board[j].push([]);
        }
    }
}

function checkSquare(x, y){
    if (typeof(board[x][y]) === ""){
        return false;
    } else {
        return true;
    }
}
initBoard();
console.log(checkSquare(3, 3));

答案 2 :(得分:-1)

两件事,第二个循环中有一个错字,它应该基于j而不是i 并且当您尝试初始化第二个数组时,您不能使用push,因为board [j]是未定义的,并且push是数组的方法

var board = [];

    function initBoard(){
        for (var i = 0; i < 8; i++){
            board.push([]);
            for (var j = 0 ;j < 8; j++){
                board[j] = [];
            }
        }
    }

    function checkSquare(x, y){
        if (typeof(board[x][y]) === ""){
            return false;
        } else {
            return true;
        }
    }
    initBoard();
    console.log(checkSquare(3, 3));