映射前修改的数组项.请解释如何



我正在编写一个JavaScript类,我有一个名为"options"的JSON对象变量,我正在修改该变量的"items"数组。

class CustomDropdown {
constructor(opt) {
this.options = {
element: opt.element,
name: opt.name,
multiChoice: opt.multiChoice === true,
callbacks: [],
items: opt.items.map(i => {
const text = i.text || "";
const it = {
text: text,
value: (i.value || text).replace(/[^A-Za-z0-9_- ]/g, "").trim(),
selected: (i.selected === true && i.selected !== undefined)
};
console.log("json obj in map func:", it);
return it;
})
};
console.log("after:", this.options.items);
//this seems to be the function messing things up.
this.fixSelectedItems();
}
fixSelectedItems() {
const itemsBefore = this.options.items;
this.debug("Fixing the items, before:", itemsBefore);
if(!this.options.multiChoice) {
let hasSelectedItem = false;
this.options.items = this.options.items.map(i => {
if(i.selected === true) {
if(selectedItem === null) {
hasSelectedItem = true;
} else {
i.selected = false;
}
}
return i;
});
if(!hasSelectedItem) {
this.options.items[0].selected = true;
}
}
this.debug("Fixed the items, after:", this.options.items);
}
}

因此,不在开发工具控制台中调用this.fixSelectedItems()打印,请执行以下操作:

json obj in map func: {text: "hm...", value: "hm", selected: false}
json obj in map func: {text: "none", value: "wow", selected: false}
json obj in map func: {text: "omg again", value: "omg again", selected: false}
after: [{text: "hm...", value: "hm", selected: false}, {text: "none", value: "wow", selected: false}, {text: "omg again", value: "omg again", selected: false}]

但是调用this.fixSelectedItems(),在记录控制台后,this.options.items会将所选this.options.items中的第一个 JSON 对象设置为 true...但是在调用此函数之前,它应该对所有函数都说 false,如果这有意义的话。

json obj in map func: {text: "hm...", value: "hm", selected: true}
json obj in map func: {text: "none", value: "wow", selected: false}
json obj in map func: {text: "omg again", value: "omg again", selected: false}
after: [{text: "hm...", value: "hm", selected: true}, {text: "none", value: "wow", selected: false}, {text: "omg again", value: "omg again", selected: false}]
Fixing the items, before: [{text: "hm...", value: "hm", selected: true}, {text: "none", value: "wow", selected: false}, {text: "omg again", value: "omg again", selected: false}]
Fixing the items, after: [{text: "hm...", value: "hm", selected: true}, {text: "none", value: "wow", selected: false}, {text: "omg again", value: "omg again", selected: false}]

抱歉,如果这看起来有点混乱,但我只是感到困惑。 为什么在调用函数之前修改数组后调用this.fixSelectedItems()?是数组映射吗?

顺便说一句,this.debug只是控制台.log。

日志中显示的对象是对实际对象本身的引用,因此,如果在查看日志之前编辑了记录的对象,则它将显示该对象的当前版本,而不是记录时的状态。

如果将控制台日志更改为以下内容(及时"深层克隆"处于该状态的对象,而不是记录对它的引用(,您将看到所需的日志。尽管值得注意的是,问题仅与日志有关,但您的代码将按预期工作。

console.log("json obj in map func:", JSON.parse(JSON.stringify(it)));

最新更新