[英]How do I get the variable value outside of EventListener function in Javascript?
[英]How do I get Javascript to remember a variable that is reset in my function, yet initially defined outside of my function?
我正在創建一個游戲,其中計算機嘗試根據用戶反饋(例如過高或過低)來猜測用戶的號碼。 我正在使用二進制搜索。 這些功能正常工作,但是,每次按下按鈕時,代碼都會重置以使原始列表從 1 變為 100,從而使猜測為 50,而不是記住在我的函數中定義的新列表和猜測。
var list = new Array(); for (i = 0; i <= 100; i++) { list.push(i) } //console.log(list) // List is intially an empty array (list). The // for loop generates integers from // 0 to 100 and pushes them into the array. var guess = list[Math.floor((list.length / 2))]; console.log(guess); var toolow = function(guess) { while (list.includes(guess) == true) { list.shift() }; var guess = list[Math.floor((list.length / 2) - 1)]; console.log(list); console.log(guess) } // toolow(guess) var toohigh = function(guess) { var last = parseInt(list.length); while (list.includes(guess) == true) { list.pop() }; var guess = list[Math.round(list.length / 2)]; console.log(list); console.log(guess) } // toohigh(guess)
<h1> Guess Your Number </h1> <button id="TooLow" onclick="toolow(guess);"> Too Low</button> <button id="TooHigh" onclick="toohigh(guess);">Too High</button>
您對變量guess
的過度使用導致了各種問題
et voila - 你的代碼現在可以工作了
var list = new Array(); for (i = 0; i <= 100; i++) { list.push(i) } //console.log(list) // List is intially an empty array (list). The // for loop generates integers from // 0 to 100 and pushes them into the array. var guess = list[Math.floor((list.length / 2))]; console.log(guess); var toolow = function() { while (list.includes(guess) == true) { list.shift() }; guess = list[Math.floor((list.length / 2) - 1)]; console.log(list); console.log(guess) } // toolow(guess) var toohigh = function() { var last = parseInt(list.length); while (list.includes(guess) == true) { list.pop() }; guess = list[Math.round(list.length / 2)]; console.log(list); console.log(guess) } // toohigh(guess)
<h1> Guess Your Number </h1> <button id="TooLow" onclick="toolow();"> Too Low</button> <button id="TooHigh" onclick="toohigh();">Too High</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.