gpt4 book ai didi

javascript - Javascript 中对象创建的异常行为

转载 作者:行者123 更新时间:2023-11-28 01:32:16 25 4
gpt4 key购买 nike

我没有通过此代码获得预期值,请帮助我找出此代码中的错误。我是java脚本的新手,我怀疑问题可能是由于对象创建或对象范围造成的。我通过多种方式进行了调试,但无法找出问题所在。

另外请告诉我我正在创建的数据是否为 ​​JSON 格式。如果不是,等效的 JSON 格式是什么?

PS.id = -1;

PS.data = {
formData:[]
};

PS.setDef = [];

PS.item = {};

if(cond){

PS.item.Name = "From";
PS.item.Type = "STRING";

PS.setDef.push(PS.item);
alert(PS.setDef[0].Name);

PS.item.Name = "To";
PS.item.Type = "STRING";

PS.setDef.push(PS.item);
alert(PS.setDef[1].Name);

}//here alerts are coming properly. getting 'from' and 'to' in alerts

PS.data.formData.push({"id":id++, "setDef":[PS.setDef[0]]});
PS.data.formData.push({"id":id++, "setDef":[PS.setDef[1]]});

//expected id 0
alert(PS.data.formData[0].id);
//expected name 'from'
alert(PS.data.formData[1].setDef[0].Name);

//expected id 1
alert(PS.data.formData[1].id);
//expected name 'to'
alert(PS.data.formData[1].setDef[1].Name);

我得到的不是 0 和 1 作为 ID,名称为“from”和“to”,而是以下值

-1
0
to
to

更新1:这里PS表示已经声明的页面范围,编辑警报以打印变量。

最佳答案

您的代码有几个逻辑错误和一个拼写错误。这是更正后的版本(更改已在注释中用 **HERE** 标记)

PS.id = -1;

PS.data = {
formData:[]
};

PS.setDef = [];

if(cond){
// *** HERE ***
// Your code was creating just one object instance in
// PS.item, pushing it, mutating and pushing it again
// The "alert" call was apparently correct just because
// it was done before mutating the object. Just moving
// both alerts at the end would have shown the problem.

PS.setDef.push({Name: "From", Type: "STRING"});
alert(PS.setDef[0].Name);

PS.setDef.push({Name: "To", Type: "STRING"});
alert(PS.setDef[1].Name);

}

// **HERE**
// id++ increments a value but returns the value BEFORE the increment.
// Thus formData[0] is expected to have .id == -1, not 0.
// If you want the value AFTER the increment then use ++id.
PS.data.formData.push({"id":++id, "setDef":[PS.setDef[0]]});
PS.data.formData.push({"id":++id, "setDef":[PS.setDef[1]]});

//expected id 0
alert(PS.data.formData[0].id);
//expected name 'from'
// *** HERE ***
// In the original code there is a typo (formData[1] instead of formData[0])
alert(PS.data.formData[0].setDef[0].Name);

//expected id 1
alert(PS.data.formData[1].id);
//expected name 'to'
alert(PS.data.formData[1].setDef[1].Name);

关于javascript - Javascript 中对象创建的异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21980506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com