javascript中的字符串连接返回" undefined"虽然变量被初始化为字符串

时间:2018-04-05 13:54:21

标签: javascript oop

所以我正在javascript上编写一个connect4。 我开始使用普通变量,给我一个迄今为止功能代码检查垂直胜利条件。

现在我已经将它重写为面向对象的类和东西。 有趣的是,代码基本上是相同的,但出于某种原因,当我试图连接表示要操纵的HTML元素的id的字符串时,连接失败并且属性获取值& #34;未定义&#34 ;.据我所知,作为此过程一部分的所有变量/属性都已在之前初始化。 出现此问题的属性在下面的代码中称为" IDmarker" 。另一个有趣的事情是,我在构建游戏场时基本上做了同样的事情,请参阅属性" this.square.id"。但是,它有效 我还尝试了很多方法,我通过" toString"将各自的变量/属性明确地设置为字符串。方法。也没用。

" this.IDmarker"通过此javascriptcode

在第44行调用被操作



this.gameFieldContainer.addEventListener('click', this.insertGamepiece,true);




这是我面向对象变体的完整JS程序代码:



// true if running in a browser, false otherwise
//const isInBrowser = typeof document !== "undefined" && document !== null;
//const isInNode = typeof module !== "undefined" && typeof module.exports !== "undefined";


class gamefield {

    constructor(){
        this.rows = 8;
        this.cols = 8;
        this.squaresize = 50;
        this.boolPlayerColor =  new Boolean ("false");
        this.PlayerColor = "";
        this.RedVictory = 0;
        this.BlueVictory = 0;
        this.VictoryTrigger = 4;
        this.lastCheckfieldVertical = 7;
        this.gameFieldContainer = document.getElementById("gamefield");
        this.column = "";
        this.IDmarker = "";
        this.checkfield = "";
        this.setNextField = "";
        this.verticalCheckfieldID = "";
        //this.buildGamefield();
        //this.insertGamepiece(); macht keinen Sinn zu initialisieren weil dann kein Klickevent vorhanden ist, was zu unerwünschtem verhalten führt.
        //this.checkForVerticalVictory();
        
    }

    buildGamefield(){
        for(var i = 0; i < this.rows; i++){
            for(var j = 0; j < this.cols; j++){
                this.square = document.createElement("div");
                this.gameFieldContainer.appendChild(this.square);
                this.square.id = 's' + i + j;
                this.topPosition = j * this.squaresize;
                this.leftPosition = i * this.squaresize;

                this.square.style.top = this.topPosition + 'px';
                this.square.style.left = this.leftPosition + 'px';

            }
        }
        this.gameFieldContainer.addEventListener('click', this.insertGamepiece,true);
        alert("ID property before insertgamepiece is " + this.IDmarker);   
    }

    insertGamepiece(selection){
        this.boolPlayerColor = !this.boolPlayerColor;
        if(this.boolPlayerColor){
            this.PlayerColor = "red";
        }else{
            this.PlayerColor = "blue";
        }//alert(this.PlayerColor)
         //alert(this.boolPlayerColor)
            document.getElementById("testfield").innerHTML = selection.target.id;
            this.column = selection.target.id.substring(1,2);
            alert("value in column is " + this.column)
        for(var a = 0; a < this.rows; a++){
            this.IDmarker = "s" + this.column + a;
            alert(this.IDmarker)
            this.checkfield = document.getElementById(this.IDmarker);
            if((this.checkfield.style.backgroundColor == "red") || (this.checkfield.style.backgroundColor == "blue")){
                this.setNextField = "s" + this.column + (a - 1);
                document.getElementById(this.setNextField).style.backgroundColor = this.PlayerColor;
                break;
            }if(((this.checkfield.style.backgroundColor != "red") && (this.checkfield.style.backgroundColor != "blue")) && (a == 7)){
                this.checkfield.style.backgroundColor = this.PlayerColor;
            }
        }
        alert("current Playercolorvalue is " + this.PlayerColor);
        //alert(this.checkfield.id);
        //alert("backgroundcolor is set to" + this.checkfield.style.backgroundColor);
        alert("ID property is " + this.IDmarker)
        
        //this.checkForVerticalVictory(this.column)
    }

    checkForVerticalVictory(checkedColumn){
        for(var b = checkedColumn; b <= checkedColumn; b++){
            for(var c = 0; c < this.rows;c++){
                this.verticalCheckfieldID = "s" + b + c;
                this.verticalCheckfield = document.getElementById(this.verticalCheckfieldID);
                if(verticalCheckfield.style.backgroundColor == "red"){
                    this.RedVictory++;
                    //alert("redvictory is " + this.RedVictory);
                }if(verticalCheckfield.style.backgroundColor == "blue"){
                    this.BlueVictory++;
                    //alert("bluevictory is " + this.BlueVictory);
                }if(this.RedVictory == this.VictoryTrigger){
                    alert("Red Wins vertical!")
                    break;
                }if(this.BlueVictory == this.VictoryTrigger){
                    alert("Blue Wins vertical!")
                    break;
                }if((this.RedVictory != 0) && (this.BlueVictory != 0)){
                    this.RedVictory = 0;
                    this.BlueVictory = 0;
                    this.cols--;
                }if((c == this.lastCheckfieldVertical) && ((this.RedVictory < 4) && (this.BlueVictory < 4))){
                    this.RedVictory = 0;
                    this.BlueVictory = 0;
                    //alert("Reset of Vertical");
                }
            }
        }
    }
}


var VierGewinnt = new gamefield();

/*
if (isInBrowser) {
	var VierGewinnt = new gamefield(); // eslint-disable-line no-unused-vars
}

if (isInNode) {
	module.exports = {
		gamefield: gamefield
	};
}
*/
&#13;
<!Doctype html>
<html>
	<head> 
		<title>Awesome game</title>
		<link rel="stylesheet" type="text/css" href="4style.css">
	<head\>
	<body onload = "VierGewinnt.buildGamefield()">
	
	<h1 id="testfield">yeah buddy </h1>
	
	<p> hier koennte ihr 4gewinnt stehen </p>
	<div id = "gamefield"></div>
	</body>
	<script type="text/javascript" src="4GewinntObjektorientiert.js"></script> 
</html>
&#13;
&#13;
&#13;

仅供参考,我还将为您提供非面向对象的代码,如果您愿意,可以在浏览器上轻松运行。因此,我还将包含css代码。

&#13;
&#13;
var rows = 8;
var cols = 8;
var squareSize = 50;
var boolPlayerColor =  new Boolean ("false")
var PlayerColor = ""
var RedVictory = 0;
var BlueVictory = 0;
var VictoryTrigger = 4;
var lastCheckfieldVertical = 7;


var gameFieldContainer = document.getElementById("gamefield");

for(i = 0; i < rows; i++){
	for(j = 0; j < cols; j++){
		var square = document.createElement("div");
		gameFieldContainer.appendChild(square);
		square.id = 's' + i + j;
		var topPosition = j * squareSize;
		var leftPosition = i * squareSize;
		
		square.style.top = topPosition + 'px';
		square.style.left = leftPosition + 'px';
	}
}

gameFieldContainer.addEventListener("click", insertGamepiece,true);

function insertGamepiece(selection){
	boolPlayerColor = !boolPlayerColor
	if(boolPlayerColor){
		PlayerColor = "red";
	}else{
		PlayerColor = "blue";
	}//alert(PlayerColor)
	document.getElementById("testfield").innerHTML = selection.target.id;
	//selection.target.style.backgroundColor = "red";
	var column = selection.target.id.substring(1,2);
	//alert("column ist " + column);
	//Structure to put the respective gamepiece
	for(a = 0; a < rows; a++){
		var ID = 's' + column + a;
		var checkfield = document.getElementById(ID)
		if((checkfield.style.backgroundColor == "red") || (checkfield.style.backgroundColor == "blue")){
			var setNextField = 's' + column + (a - 1);
			document.getElementById(setNextField).style.backgroundColor = PlayerColor;
			break;
			
		}if(((checkfield.style.backgroundColor != "red") && (checkfield.style.backgroundColor != "blue")) && (a == 7)){
			checkfield.style.backgroundColor = PlayerColor;
		}
		/*
		if((column + a) == (column + 7)){
		var destination = column + a;
		alert("destination ist " + destination);
		document.getElementById("testparagraph").innerHTML = destination.toString();
		}*/
	}
	checkForVerticalVictory(column);
	//checkForHorizontalVictory(); nested into function "checkForVerticalVictory"
}

function checkForVerticalVictory(checkedColumn){
	for(b = checkedColumn; b <= checkedColumn; b++){
		for(c = 0; c < rows; c++){
			var verticalCheckFieldID = 's' + b + c
			var verticalCheckField = document.getElementById(verticalCheckFieldID);
			if(verticalCheckField.style.backgroundColor == "red"){
				RedVictory++;
				//alert("redvictory is " + RedVictory);
			}if(verticalCheckField.style.backgroundColor == "blue"){
				BlueVictory++;
				//alert("bluevictory is " + BlueVictory);
			}if(RedVictory == VictoryTrigger){
				alert("Red Wins vertical!")
				break;
			}if(BlueVictory == VictoryTrigger){
				alert("Blue Wins vertical!")
				break;
			}if((RedVictory != 0) && (BlueVictory != 0)){
				RedVictory = 0;
				BlueVictory = 0;
				cols--;
			}if((c == lastCheckfieldVertical) && ((RedVictory < 4)&&(BlueVictory < 4))){
				RedVictory = 0;
				BlueVictory = 0;
				//alert("Reset of Vertical");
			}
		}
	}
}
&#13;
body {
    margin: 60px auto;
    width: 70%;
    max-width: 950px;
}

h1 {
    font-size: 3em;
    font-family:'Helvetica', 'Arial', 'Sans-Serif';
}


#gamefield {
	position:relative;
	margin:0 auto 2em auto;
	width:500px;
	height:500px;
}

#gamefield div {
	position:absolute;
	-webkit-box-sizing: border-box; /* Safari 3.0 - 5.0, Chrome 1 - 9, Android 2.1 - 3.x */
	-moz-box-sizing: border-box;    /* Firefox 1 - 28 */
	box-sizing: border-box;         /* Safari 5.1+, Chrome 10+, Firefox 29+, Opera 7+, IE 8+, Android 4.0+, iOS any */
	background: #f6f8f9; /* Old browsers */
	border: 1px solid #ddd;
	width:50px;
	height:50px;
}
&#13;
<!Doctype html>
<html>
	<head> 
		<title>Awesome game</title>
	 	<link rel="stylesheet" type="text/css" href="4style.css">
	<head\>
	<body>
	
	<h1 id="testfield">yeah buddy </h1>
	
	<p> hier koennte ihr 4gewinnt stehen </p>
	<div id = "gamefield"></div>
	</body>

</html>

<script type="text/javascript" src="4gewinnt.js"></script>
&#13;
&#13;
&#13;

0 个答案:

没有答案