所以我在rails中制作一个小型闪存卡应用程序,我正在使用javascript作为卡逻辑。我是JS的新手,我遇到了resetting
variables
根据我的front
的结果back
和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>
的问题
randomCard
当我运行elem.innerHTML = rand.back;
函数时rand.back
更新了新的&#39; rand.back&#39;但是当我翻转卡片时,rand.front&#39;并且public static int triangular(int n){
if(n <= 0) return 0;
for (int i = 0; i < n; i++) {
System.out.print("* ");
}
System.out.println();
return n + triangular(n - 1);
}
返回会话开始时设置的初始值。我如何具体更新这些值?
答案 0 :(得分:1)
在randomCard
函数中,每次执行函数时,您都会在此函数的本地范围内创建新的front
和back
变量,并使用var
声明变量。
由于名称为front
和back
的变量现在位于此函数的本地范围内,因此赋值发生在本地front
和back
变量上,因为它们存在于直接背景;它不必查看randomCard
函数之外的上下文,其中要更新front
和back
变量。
为了获得您想要的行为,只需不要在front
内使用back
关键字声明var
和randomCard
变量,以便任何分配到它们发生在外front
和back
答案 1 :(得分:-3)
替换
var rand = cards[Math.floor(Math.random() * cards.length)];
与
rand = cards[Math.floor(Math.random() * cards.length)];