gpt4 book ai didi

javascript - 数组 slice() 给出的是引用而不是值

转载 作者:太空狗 更新时间:2023-10-29 18:12:41 25 4
gpt4 key购买 nike

我有一个文件,我要在其中导出这样的对象:

export const LINECHART2_DATA = {
series: [{
data: [],
name: 'HR',
},
{
etc...
}]
}

我是这样导入的:

import { LINECHART2_DATA } from '../chart-options/options';

我有以下方法:

prepareLineChartDataContainer(bed: BedDetails) {
//Clear data to prepare for new bed
if (bed.seriesContainer == null) {
bed.seriesContainer = LINECHART2_DATA.series.slice();
} else {
bed.seriesContainer.forEach(series => {
series.data.length = 0;
});
}
//Add data to seriesContainer
this.vitalSigns.forEach(vs => {
bed.timeWindows.forEach(tw => {
bed.seriesContainer.find(series => series.name == vs).data.push(tw['avg' + vs]);
});
});
}

正如您在上面看到的,我正在从 LINECHART2_DATA 中分割系列数组,然后向其推送一些数据。当一个新的 bed传递给带有 null seriesContainer 的方法, 它将再次被切片,但这次它将包含前一个 bed 添加的数据。 .因为我正在使用 slice() ,我原本希望得到 LINECHART2_DATA 的值,不是引用。我做错了什么?

最佳答案

来自documentation of Array.slice :

slice does not alter the original array. It returns a shallow copy ofelements from the original array. Elements of the original array arecopied into the returned array as follows:

For object references (and not the actual object), slice copies objectreferences into the new array. Both the original and new array referto the same object. If a referenced object changes, the changes arevisible to both the new and original arrays.

For strings, numbers andbooleans (not String, Number and Boolean objects), slice copies thevalues into the new array. Changes to the string, number or boolean inone array do not affect the other array. If a new element is added toeither array, the other array is not affected.

所以您看到的行为是 slice 的浅拷贝行为的结果。如果您需要深拷贝以便可以在不影响原始对象的情况下自由改变对象,则需要手动进行。 The answers to this question显示一些这样做的方法。

关于javascript - 数组 slice() 给出的是引用而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49700329/

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