英文:
How to push a map in array and clear the original map to store more data
问题
我正在使用一个地图来存储名称和数字作为K,V对。我正在使用for循环来运行并在此地图中存储多个数据集。期望的行为是循环将被执行,并且值将被存储在地图中,然后我想将此地图推入一个数组中,并清除原始地图以存储另一个数据集。我的问题是,当我尝试清除原始地图时,它也会擦除已保存在数组中的数据。
我尝试过使用深拷贝,但它不起作用。是否有其他方法可以做到这一点?
以下是我的代码。
for (let GUId of GUIIds) {
if (GUId.toLowerCase() != parentGUI.toLowerCase()) {
await browser.driver.switchTo().window(GUId);
for (let j = 0; j < (await this.elePanels.count()); j++) {
if (j != 0) await this.elePanels.get(j).click();
let name = await this.elePanels
.get(j)
.getWebElement()
.findElement(By.xpath(".//mat-panel-title"))
.getText();
let number = await this.elePanels
.get(j)
.getWebElement()
.findElement(
By.xpath(
".//span[@class='ng-star-inserted']//following-sibling::span"
)
)
.getText();
await map.set(name, number);
}
await actualData.push(map);
await map.clear();
await browser.driver.close();
await browser.driver.switchTo().window(parentGUI);
}
return actualData;
}
英文:
I am using one map to store name and number as K,V pair. I am using a for loop to run and store multiple data sets in this map. The expected behavior is a loop that will be executed and values will be stored in the map, then I want to push this map into an array and clear the original map to store another data set. My problem is when I try to clear the original map it wipes the data that has been saved in an array as well.
I tried using deep copy but it is not working. Is there any other way to do it?
Below is my code.
for (let GUId of GUIIds) {
if (GUId.toLowerCase() != parentGUI.toLowerCase()) {
await browser.driver.switchTo().window(GUId);
for (let j = 0; j < (await this.elePanels.count()); j++) {
if (j != 0) await this.elePanels.get(j).click();
let name = await this.elePanels
.get(j)
.getWebElement()
.findElement(By.xpath(".//mat-panel-title"))
.getText();
let number = await this.elePanels
.get(j)
.getWebElement()
.findElement(
By.xpath(
".//span[@class='ng-star-inserted']//following-sibling::span"
)
)
.getText();
await map.set(name, number);
}
await actualData.push(map);
await map.clear();
await browser.driver.close();
await browser.driver.switchTo().window(parentGUI);
}
return actualData;
答案1
得分: 1
数组是JavaScript中的引用类型,当一个变量被分配给它时,它指向数组的引用,而不是值。你之所以出现这个错误,是因为actualData
存储了map
数组的引用,而不是值。
要修复这个问题,可以使用array.slice()
,因为array.slice()
返回数组的值,而不是引用。
const actualData = [];
...
actualData.push(map.slice(0));
你可以在这里了解更多信息。
英文:
Array is a reference type in Javascript and when a variable is assigned to it, it points to the reference of the array, not the value. You are getting this error because actualData
stores the reference of map
array not the value.
To fix this, use array.slice()
because array.slice()
returns the value of the array and not a reference.
const actualData = [];
...
actualData.push(map.slice(0))
You can read more about it here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论