我是javascript的初学者,我为使用数组对象的蛇和梯子编写了一个javascript程序,但是我无法理解如何使用其开始和结束位置调用变量snake_pos。这是代码:
var player_pos = 4;
var dice_value = Math.floor(Math.random() * 6) + 1;
function dice() {
player_pos = player_pos + dice_value;
}
dice();
var last_pos = 25;
function game_rule() {
if (player_pos >= last_pos)
{
alert("won the game");
}
}
game_rule();
function snake() {
var snake_pos = [{
start_pos: 11,
end_pos: 4
},
{
start_pos: 20,
end_pos: 7
},
{
start_pos: 24,
end_pos: 3
}
]
}
console.log(player_pos);
console.log(dice_value);
console.log(snake_pos);

答案 0 :(得分:0)
您必须return
变量snake_pos
才能在函数外部使用它。之后,您可以调用array
和object
中的项目,看一下这个例子:
function snake(){
// return the variable to use it outside the function
return snake_pos = [
{start_pos:11, end_pos:4},
{start_pos:20, end_pos:7},
{start_pos:24, end_pos:3}
]
}
//store the returned value in a variable
snake_pos = snake();
//log the first array item start_pos
console.log(snake_pos[0].start_pos);
//log the second array item start_pos
console.log(snake_pos[1].start_pos);
答案 1 :(得分:0)
只需在您尝试访问它的同一范围内声明snake_pos
:
var player_pos = 4;
var dice_value = Math.floor(Math.random() * 6) + 1;
// declare it here
var snake_pos = [{
start_pos: 11,
end_pos: 4
},
{
start_pos: 20,
end_pos: 7
},
{
start_pos: 24,
end_pos: 3
}
];
function dice() {
player_pos = player_pos + dice_value;
}
dice();
var last_pos = 25;
function game_rule() {
if (player_pos >= last_pos)
{
alert("won the game");
}
}
game_rule();
function snake() {
// It will be accessible here as well
}
console.log(player_pos);
console.log(dice_value);
// It will be accessible here
console.log(snake_pos);

答案 2 :(得分:0)
检查以下代码并尝试了解其工作原理。
// declear global variables here
var player_pos = 4;
var last_pos = 25;
var dice_value = Math.floor(Math.random()*6)+1;
// function to play dice add dice value
function dice(){
dice_value = Math.floor(Math.random()*6)+1;
player_pos = player_pos + dice_value;
}
// we have snake positions in this, we check user on snake position or not we will do action accordingly
function snake(){
var snake_pos = [
{start_pos:11, end_pos:4},
{start_pos:20, end_pos:7},
{start_pos:24, end_pos:3}
];
for(var i =0; i < snake_pos.length; i++) {
if(snake_pos[i].start_pos == player_pos) {
player_pos = snake_pos[i].end_pos;
}
}
}
// in this we define game rule, if user won we return true
function game_rule(){
if (player_pos >= last_pos)
{
alert("won the game");
return true;
} else {
return false;
}
}
// we play game until user won this game
while(game_rule() != true) {
console.log(player_pos);
console.log(dice_value);
dice();
snake();
}
如果您有任何疑问,请告诉我。
快乐编码!!!
答案 3 :(得分:0)
function Snake() {
this.snake_pos = [{
start_pos: 11,
end_pos: 4
},
{
start_pos: 20,
end_pos: 7
},
{
start_pos: 24,
end_pos: 3
}
]
}
var snake = new Snake();
console.log(snake.snake_pos[0].start_pos);
请检查:https://www.phpied.com/3-ways-to-define-a-javascript-class/