gpt4 book ai didi

javascript - 在声明范围之外使用局部变量;为什么这有效?

转载 作者:行者123 更新时间:2023-12-01 05:49:05 25 4
gpt4 key购买 nike

我从网站上获得了这个游戏演示,并注意到了这段代码:

if(nx == food.x && ny == food.y) {
var tail = {x: nx, y: ny};
score++;
create_food();
} else {
var tail = snake_array.pop();
tail.x = nx; tail.y = ny;
}

snake_array.unshift(tail); //how is tail used here?

我没有找到“tail”变量的任何其他声明,那么这是怎么发生的呢?我对这个编程领域(网络开发/脚本语言)还很陌生,所以我不确定这是否允许。

完整代码:

$(document).ready(function(){
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();

var cw = 10;
var d;
var food;
var score;

var snake_array;

function init() {
d = "right";
create_snake();
create_food();
score = 0;

if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);
}
init();

function create_snake() {
var length = 5;
snake_array = [];
for(var i = length-1; i>=0; i--) {
snake_array.push({x: i, y:0});
}
}

function create_food() {
food = {
x: Math.round(Math.random()*(w-cw)/cw),
y: Math.round(Math.random()*(h-cw)/cw),
};
}

function paint() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);

var nx = snake_array[0].x;
var ny = snake_array[0].y;

if(d == "right") nx++;
else if(d == "left") nx--;
else if(d == "up") ny--;
else if(d == "down") ny++;

if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array)) {
init();
return;
}

/* @@@@@@@@@ This is where it is happening @@@@@@@@@ */
if(nx == food.x && ny == food.y) {
var tail = {x: nx, y: ny};
score++;
create_food();
} else {
var tail = snake_array.pop();
tail.x = nx; tail.y = ny;
}

snake_array.unshift(tail);

for(var i = 0; i < snake_array.length; i++) {
var c = snake_array[i];
paint_cell(c.x, c.y);
}

paint_cell(food.x, food.y);
var score_text = "Score: " + score;
ctx.fillText(score_text, 5, h-5);
}

function paint_cell(x, y) {
ctx.fillStyle = "blue";
ctx.fillRect(x*cw, y*cw, cw, cw);
ctx.strokeStyle = "white";
ctx.strokeRect(x*cw, y*cw, cw, cw);
}

function check_collision(x, y, array) {
for(var i = 0; i < array.length; i++) {
if(array[i].x == x && array[i].y == y)
return true;
}
return false;
}

$(document).keydown(function(e) {
var key = e.which;
if(key == "37" && d != "right") d = "left";
else if(key == "38" && d != "down") d = "up";
else if(key == "39" && d != "left") d = "right";
else if(key == "40" && d != "up") d = "down";
})
})

代码来源:http://thecodeplayer.com/walkthrough/html5-game-tutorial-make-a-snake-game-using-html5-canvas-jquery

如有任何帮助,我们将不胜感激:)

最佳答案

tail 是在 if 语句中声明的,因此它的范围不受该语句的限制。如果它在函数中,您就会失去作用域。

正如评论中所说,JavaScript 仅具有函数级作用域。

这是一个可以在控制台中运行的简单示例:

if (1>0) {
var derp = "herp";
}
console.log(derp);
//outputs "herp"

关于javascript - 在声明范围之外使用局部变量;为什么这有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com