如果访问静态(非常奇怪),JS-Object会丢失值

时间:2014-10-15 08:29:07

标签: javascript object

我很困惑。问题是对象在循环中丢失其值,具体取决于您访问它的方式。如果我通过变量访问一切正常。如果我使用静态表达式(与变量相同),我就没有正确的值。 但是,让我们看一下代码:

功能本身:

//Creating function with an input parameter (inputString)
function weirdBehaviour(inputString){

    //initializing the outputObject which will be returned
    var outputObject = {PROP1: "", PROP2: ""}

    // Loop through the return-Object
    for(x in outputObject){

        // Split input at <PROP1> etc. 
        var res = inputString.split("<" + x.toString() + ">");
        // Split "splitted input" again at </PROP1> etc.
        var res2 = res[1].split("</" + x.toString() + ">");

        // res2[0] is now the String between <PROP1></PROP1>
        outputObject.x = res2[0];

        // Log gives x and the value assigned to x
        console.log("-LOOP-START--------------------------------------");
        console.log("This works: ");
        // This works just fine
        console.log(x.toString() + ": " + outputObject.x);

        console.log("This doesn't: ");
        // Should be exactly the same but isn't
        console.log("PROP1: " + outputObject.PROP1);
        console.log("PROP2: " + outputObject.PROP2);
        console.log("-LOOP-END----------------------------------------");
    }
}

访问示例:

weirdBehaviour("<PROP1>String between prop1-tags</PROP1><PROP2>Prop2-Tag-String</PROP2>");

输出:

PROTOKOLL: -LOOP-START-------------------------------------- 
PROTOKOLL: This works:  
PROTOKOLL: PROP1: String between prop1-tags 
PROTOKOLL: This doesn't:  
PROTOKOLL: PROP1:  
PROTOKOLL: PROP2:  
PROTOKOLL: -LOOP-END---------------------------------------- 
PROTOKOLL: -LOOP-START-------------------------------------- 
PROTOKOLL: This works:  
PROTOKOLL: PROP2: Prop2-Tag-String 
PROTOKOLL: This doesn't:  
PROTOKOLL: PROP1:  
PROTOKOLL: PROP2:  
PROTOKOLL: -LOOP-END---------------------------------------- 

我很困惑......太奇怪了。 我希望有人能帮帮忙。

谢谢和问候, OL

2 个答案:

答案 0 :(得分:2)

在这一行:

outputObject.x = res2[0];

您要在名为x的对象上创建属性,而不是使用x中存储的名称创建属性。为此,请使用括号表示法:

outputObject[x] = res2[0];

......以及稍后阅读时:

console.log(x + ": " + outputObject[x]);

(您不需要使用x.toString()x已经是字符串。)

在JavaScript中,您可以使用点表示法和属性名称​​ literal obj.foo)或括号表示法和属性名称​​ string ({ {1}})。在括号表示法中,字符串可以是任何表达式的结果,包括变量查找。所以这些都是相同的,例如:

obj["foo"]

答案 1 :(得分:1)

您应该使用:

outputObject[ x ] = res2[0];

而不是

outputObject.x