This question already has answers here:
JavaScript closure inside loops – simple practical example
                                
                                    (44个回答)
                                
                        
                3年前关闭。
            
        

我的阵列:

     var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];


将功能设置为按钮:



var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

for (var idx = 0; idx < alphabet.length; idx++) {
  var bttn = document.createElement("button");
  bttn.innerText = alphabet[idx];
  bttn.onclick = function() {
    this.disabled = true;
    checkIfWordContainLetter(alphabet[idx]);
  }
  document.getElementById("hangmanContent").appendChild(bttn);
}

function checkIfWordContainLetter(letter) {
  alert(wordToGuess);
  alert(letter);
}





当我通过undefined作为参数时会导致alphabet[idx],但是如果我通过例如'a'则会提示a

最佳答案

试试下面的代码:



var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
for(var idx=0;idx<alphabet.length;idx++)
		{
			var bttn = document.createElement("button");
			bttn.innerText = alphabet[idx];

			bttn.onclick = function () {this.disabled=true;

			checkIfWordContainLetter(this.innerText);
			}
			document.getElementById("hangmanContent").appendChild(bttn);
		}



function checkIfWordContainLetter(letter)
	{
		alert(letter);
		alert(letter);

	}

<body>
<div id="hangmanContent"></div>
</body>

关于javascript - 将数组值作为参数传递会导致未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40703937/

10-11 12:51