1

我想使用两个字符串(t know their content) to create two nameSpace.And i don如果名称空间存在,我不想创建一个新字符串。这是我的代码:

function createNameSpace(nameSpace)
{
    var spaceArr = nameSpace.split(".");
    var curSpace = window;

    //judge if this nameSpace exists.
    var i;
    for(i in spaceArr)
    {
        curSpace = curSpace[spaceArr[i]];
        if(curSpace)
            window.alert("nameSpace1:" + nameSpace + "\ncurSpace do exists:" + curSpace + "\ni:" + i + "\nspaceArr[i]:" + spaceArr[i] + "|");
        else
        {
            curSpace = {};
            window.alert("nameSpace1:" + nameSpace + "\ncurSpace not found:" + curSpace + "\ni:" + i + "\nspaceArr[i]:" + spaceArr[i] + "|");
            break;
        }
    }

    //now curSpace must have been created.
    i++;
    //window.alert("nameSpace2:" + nameSpace + "\ni:" + i + "\nspaceArr.length:" + spaceArr.length);
    //create the nameSpace
    for(;i < spaceArr.length; i++)
    {
        //window.alert("nameSpace2:" + nameSpace + "\ni:" + i + "\nspaceArr.length:" + spaceArr.length);
        if(i == 0)
        {
            window[spaceArr[i]] = {};
            curSpace = window[spaceArr[i]];
        }
        else
        {
            //window.alert("nameSpace3:" + nameSpace + "\ncurSpace[spaceArr[i]]:" + curSpace[spaceArr[i]]);
            curSpace[spaceArr[i]] = {};
            curSpace = curSpace[spaceArr[i]];
        }
    }
    return curSpace;
}

问题是,如果我将“myTest.myNameSpace”和“myTest.monaNameSpace”发送到这个函数中,当我发送“myTest.monaNameSpace”时,它都会提示“curSpace not found”,应该是“curSpace do exists:”。我不知道错误在哪里,有人可以告诉我吗?

4

1 回答 1

0

我认为你的算法有点复杂。我对其进行了一些重构,并为其添加了一个测试并验证它在控制台中工作。我也多次写过这段代码,所以我很确定我已经达到了你的要求

function createNameSpace(nameSpace)
{
    var spaceArr = nameSpace.split(".");
    var curSpace = window;

    //judge if this nameSpace exists.
    var i = 0;
    for(i = 0;i < spaceArr.length; i++)
    {
        var next = spaceArr[i];
        console.log(curSpace, next);
        if(curSpace[next] == undefined)
        {
            curSpace[next] = {};
            curSpace = curSpace[next]
        }
        else
        {
            curSpace = curSpace[next];
        }
    }

    return curSpace;
}
createNameSpace("myTest.myNameSpace");
console.log(myTest.myNameSpace);
myTest.myNameSpace.myName = "Leat Hakkor";
createNameSpace("myTest.monaNameSpace");
console.log(myTest.monaNameSpace);
console.log(myTest.myNameSpace.myName);
于 2014-02-15T16:43:05.470 回答