简体   繁体   English

为什么此值等于“未定义”? (javascript)

[英]Why does this value equal to 'undefined'? (javascript)

I have a function for finding on which tile the mouse is on: 我有一个函数可以找到鼠标在哪个图块上:

function testTile(mouseX, mouseY){
    if(mouseX<mapArray[0].length*20 && mouseY<mapArray.length*20){
        var tile = getTilePosition(mouseX-10, mouseY-10);
        selectedtile.x = tile.xtile, 
        selectedtile.y = tile.ytile;
    }
}

and a function for getting the tile position given x and y 以及给定x和y来获得图块位置的函数

function getTilePosition(x, y){
    var xtile = Math.floor(x/20);
    var ytile = Math.floor(y/20);
return{
    xtile : xtile,
    ytile : ytile
    }
}

but when I call selectedtile.x or selectedtile.y I get a value of 'undefined'. 但是当我调用selectedtile.x或selectedtile.y时,得到的值是'undefined'。 What's wrong? 怎么了?

It appears your values are declared inside the function and are out of scope. 您的值似乎在函数内部声明并且超出范围。

Do this: 做这个:

var selectedtile = new Object() //de OUTSIDE All functions.
//de this works too: var selectedtile = {}

function testTile(mouseX, mouseY){
    if(mouseX<mapArray[0].length*20 && mouseY<mapArray.length*20){
        var tile = getTilePosition(mouseX-10, mouseY-10);
        selectedtile.x = tile.xtile, 
        selectedtile.y = tile.ytile;
    }
}

function getTilePosition(x, y){
    var xtile = Math.floor(x/20);
    var ytile = Math.floor(y/20);
    return {
        xtile : xtile,
        ytile : ytile
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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