为什么这个值等于'undefined'? (JavaScript的)

时间:2013-12-08 22:14:56

标签: javascript object tile

我有一个函数可以找到鼠标在哪个磁贴上:

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;
    }
}

和获取给定x和y

的平铺位置的函数
function getTilePosition(x, y){
    var xtile = Math.floor(x/20);
    var ytile = Math.floor(y/20);
return{
    xtile : xtile,
    ytile : ytile
    }
}

但是当我调用selectedtile.x或selectedtile.y时,我得到的值是'undefined'。怎么了?

1 个答案:

答案 0 :(得分:0)

看来你的值是在函数内声明的,超出了范围。

这样做:

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
    }
}