Javascript返回不起作用

Sna*_*SWE 1 javascript jquery return

我有这个代码:

function get_id_from_coords (x, y)
{
    x = parseInt(x);
    y = parseInt(y);

    if (x < 0)
    {
        x = (x + 6) * 60;
    }
    else
    {
        x = (x + 5) * 60;
    }
    if (y < 0)
    {
        y = (y + 6) * 60;
    }
    else
    {
        y = (y + 5) * 60;
    }

    $('#planets').children().each(function(){
        if ($(this).attr('x') == x) {
            if ($(this).attr('y') == y) {
                alert (parseInt($(this).attr('id')));
                return parseInt($(this).attr('id'));
            }
        }
    });
}
alert(get_id_from_coords(x, y));
Run Code Online (Sandbox Code Playgroud)

但是,从这段代码我得到两个弹出窗口:首先,从函数内部,我得到正确的值(如63),但是当我提醒返回值时,我只是得到了未定义.

icy*_*com 6

由于函数没有返回,因此未定义 - 最后一个语句是对each函数的调用,而不是return语句.如果你回报,例如

...
return $('#planets').children().each(function(){
    if ($(this).attr('x') == x) {
        if ($(this).attr('y') == y) {
            alert (parseInt($(this).attr('id')));
            return parseInt($(this).attr('id'));
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

它将返回一些东西 - 在这种情况下,基于文档:

它会让孩子们回归#planets.

如果你想找到一些专门使用的值each,那么你可以这样做:

...
val toRet;
$('#planets').children().each(function(){
    if ($(this).attr('x') == x) {
        if ($(this).attr('y') == y) {
            toRet = parseInt($(this).attr('id'));
        }
    }
});
return toRet;
Run Code Online (Sandbox Code Playgroud)