繁体   English   中英

我的函数不会在 for 循环中返回对象

[英]My function doesn't not return object in a for loop

我创建了一个函数,它采用 XML 字符串中标签S的内部:

'<C><P /><Z><S>[Grounds here]</S><D /><O /></Z></C>'

,包含场地数据,显然与游戏有关。 然后我消耗这个内部的每个地面数据,直到我在我的for循环中使用i达到数字z并将第一个/一个剩余地面的数据作为对象返回。

问题:函数返回undefined而不是object


这是函数:

/**
 * Get a string between 2 strings.
 */
String.prototype.between = function(left, right) {
    var sub = this.substr(this.lastIndexOf(left) + left.length);
    return sub.substr(0, sub.indexOf(right));
}

/**
 * @param {Number} z The inner position of the ground I want to read, e.g, 1, the first.
 */
function readGround(z) {

     // string containing all existent grounds
    var groundsData = xml.substr(STG.indexOf('<S>') + 3, STG.lastIndexOf('</S>'));

     // Iterate the grounds while z isn't reached
    for(var i = 1; i < z; i++) {

        // Get the ground inner
        var outer = groundsData.substr(groundsData.indexOf('<S') + 3, groundsData.indexOf('/>'));

        // Check if i reached z
        if(i === z) {

            // Get grounds properties
            var a = [
                outer.between('L="', '"'),
                outer.between('H="', '"'),
                outer.between('X="', '"'),
                outer.between('Y="', '"')
            ];

            return {
                L: a[0], H: a[1],
                X: a[2], Y: a[3]
            };

        // Else skip this ground
        } else groundsData = groundsData.substr(groundsData.indexOf('/>'), groundsData.length);
    }
}

你的循环使i1num-1 但是在循环中你有一个条件if(i==num) 此条件永远不会为真,因此程序永远不会到达return语句。 如果函数内部的程序流意味着永远不会到达return语句,那么该函数只会返回undefined (这不是特定于 javascript 的 - 类似的规则适用于许多语言。)

相反,您可以将return语句移到循环之外

function readGround(num) {
    var grounds = stg.substr(stg.indexOf('<S>') + 3, stg.lastIndexOf('</S>')),
        gr;
    for (var i = 1; i < num; i++) {
        grounds = grounds.substr(grounds.indexOf('/>') + 2, grounds.length);
    }
    gr = grounds.substr(grounds.indexOf('<S') + 3, grounds.indexOf('/>'));
    var a = [stringBetween(gr, 'L="', '"'), stringBetween(gr, 'H="', '"'), stringBetween(gr, 'X="', '"'), stringBetween(gr, 'Y="', '"')];
    return {
        L: a[0],
        H: a[1],
        X: a[2],
        Y: a[3]
    };
}

(还必须调整其他一些事情才能使您的代码正常工作,例如a应该从gr的文本部分而不是从更长的字符串grounds读取)

提琴手

暂无
暂无

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

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