简体   繁体   中英

Trying to set a global variable with javascript function

So I am making a small flash card app in rails and I am using javascript for the card logic. I am new to JS and I am having some trouble resetting the variables I am using for the cards front and back based on the outcome of my randomizing function

<script>
var card_list = "<%=j @deck.cards.to_json.html_safe %>";
console.log(card_list)

/* Parse the Json and get all the cards */
var cards = JSON.parse(card_list);

/* Return json object count */
var length = Object.keys(cards).length;
console.log(length)

/* Grab a random card from the card list */
var rand = cards[Math.floor(Math.random() * cards.length)];
console.log(rand)

/* Set the front label from random value */
var front = rand.front;
console.log(front)

/* Set the back label from random value */
var back = rand.back;
console.log(back)

/* Grab the div and set the label */
var elem = document.getElementById("card-face");
elem.innerHTML = rand.back;

/* Grab another random card from the card list */
function randomCard() {
 var rand = cards[Math.floor(Math.random() * cards.length)];
 console.log(rand)
 if (typeof front !== 'undefined') {
 alert("Undefined");
 }
 else{
 var front = rand.front;
 var back = rand.back;
 console.log("Should now be updated?")
 };
 var elem = document.getElementById("card-face");
 elem.innerHTML = rand.back;
}

/* Flip the card front to back */
function flipper() {
 var elem = document.getElementById("card-face");
 if (elem.innerHTML== rand.front) elem.innerHTML = rand.back;
 else elem.innerHTML = rand.front;
console.log(elem)
}
</script>

When I run the randomCard function elem.innerHTML = rand.back; is updated with the new 'rand.back' but when I flip the card 'rand.front' and rand.back returns the initial values I set when the session started. How can I updated these values specifically?

Inside your randomCard function, you are creating new front and back variables inside this function's local scope every time you are executing the function and declare the variables with var .

Since variables with the names front and back now live inside this function's local scope, the assignment happens on the local front and back variables, since they exist in the immediate context; it doesn't have to look to the context outside of the randomCard function where the front and back variables you want to update live.

In order to get the behaviour you want simply do not declare the front and back variables with the var keyword, inside your randomCard , so that any assignments to them happen to the outer front and back

replace

 var rand = cards[Math.floor(Math.random() * cards.length)];

with

 rand = cards[Math.floor(Math.random() * cards.length)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM