JS对象在访问静态时会丢失值(非常奇怪)

JS-Object loses values if accessed static (very weird)

本文关键字:非常 对象 访问 静态 JS      更新时间:2023-09-26

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

函数本身:

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

在这一行:

outputObject.x = res2[0];

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

outputObject[x] = res2[0];

类似地,当你读到它时:

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

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

在JavaScript中,您可以使用点表示法和属性名称literalobj.foo),或者使用方括号表示法和特性名称

obj.foo
obj["foo"]
x = "foo"; obj[x]
obj["f" + "o" + "o"]

您应该使用:

outputObject[ x ] = res2[0];

而不是

outputObject.x