Javascript在未被告知的情况下更改数组值

Javascript在未被告知的情况下更改数组值,javascript,arrays,reactjs,javascript-objects,Javascript,Arrays,Reactjs,Javascript Objects,我是Javascript新手,因此这个问题可能很简单,但我无法找到答案 我有一个带有几个参数(如名称、面积、ppm等)的类国家,还有一个函数updateCurrentData(input1、input2),它根据输入将当前值更改为新值。然后,我有一个类PPM_Data,它具有以下功能: initialCountries = []; copyData = []; PPMPerCountryPerYear(year, inputPopulation, inputDeforestatio

我是Javascript新手,因此这个问题可能很简单,但我无法找到答案

我有一个带有几个参数(如名称、面积、ppm等)的类国家,还有一个函数updateCurrentData(input1、input2),它根据输入将当前值更改为新值。然后,我有一个类PPM_Data,它具有以下功能:

  initialCountries = [];
  copyData = [];

  PPMPerCountryPerYear(year, inputPopulation, inputDeforestation) {
    var result = [];
    this.copyData = this.initialCountries.slice(0);
    console.log(this.copyData);
    console.log(this.initialCountries);

    result.push({2020: this.initialCountries});
    for (let index = 2021; index <= year; index++) {

        this.copyData.forEach(c => {
            c.updateCurrentData(inputPopulation, inputDeforestation);
        })

        let yearData = [];

        this.copyData.forEach(c => {
            yearData.push(c);
        });

        result.push({ [index]: yearData });

    }

    return result;
}
其中数组包含每个国家今年的数据(假设有12个国家)。值每年都会发生一些变化,我想这是因为我得到了一个包含所有年份的数组,但数组是相同的,它等于循环的最后一次计算

我使用d3从csv文件加载国家的初始国家:

loadCountries(path) {
    var self = this;
    var readCsv = d3.csv(path, function (data) {
        var country = new Country(data.name, Number(data.area), Number(data.ppm), Number(data.population), Number(data.population_growth), Number(data.forests_percentage), Number(data.forests_growth));
        self.initialCountries.push(country);
    });

    return readCsv;
}
loadCountries函数在App.js中的componentWillMount()函数中调用


当我点击一个按钮时,我调用了PPMPerCountryPerYear函数,正如您所看到的,在调用for循环之前,我将console.log initialCountries记录在begging中。除此之外,我没有调用initialCountries数组上的任何更改,但是控制台日志的输出是最后更新的值,即使for循环还没有启动。我的问题是为什么会发生这种情况,以及如何防止initialCountries数组发生更改?

我认为Javascript的“按引用传递”特性给您带来了麻烦

这意味着在JS中,如果您使用更大的对象,比如对象{},数组[],如果您基于另一个对象创建一个,比如

var a = {a: 'a'}
var b = a

a.a='x'

console.log(a.a) // x
console.log(b.a) // x

我建议您放置一些调试器语句,因为它们比控制台日志语句更可靠,您会对不同的结果感到惊讶

我创建了一个函数,将对象逐个添加到copyData数组中,这使两个数组的对象完全不同,但当我添加调试器并循环时,每次调用updateCurrentData函数时,我都会看到intialCountries数组是如何变化的(即使我在copyData数组上调用它)
var a = {a: 'a'}
var b = a

a.a='x'

console.log(a.a) // x
console.log(b.a) // x