【问题标题】:Javascript changing array values without being told toJavascript更改数组值而不被告知
【发布时间】:2020-08-05 10:20:12
【问题描述】:

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

我有一个 Country 类,它带有一些参数(即名称、面积、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;
}

结果应该返回一个数组,其中包含每个国家/地区的值,例如:

{ 2020: Array(12) },
{ 2021: Array(12) }
...

其中数组包含今年每个国家/地区的数据(假设有 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;
}

在 App.js 的 componentWillMount() 函数中调用 loadCountries 函数。

当我单击一个按钮时,我会调用 PPMPerCountryPerYear 函数,正如您所看到的,我在调用 for 循环之前在开始时 console.log 中的 initialCountries。最重要的是,我没有在 initialCountries 数组上调用任何更改,但控制台日志的输出是最后更新的值,即使 for 循环甚至还没有开始。我的问题是为什么会发生这种情况,如何防止 initialCountries 数组发生变化?

【问题讨论】:

    标签: javascript arrays reactjs javascript-objects


    【解决方案1】:

    我认为 Javascript 的“通过引用传递”性质是给您带来麻烦的原因。

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

    var a = {a: 'a'}
    var b = a
    
    a.a='x'
    
    console.log(a.a) // x
    console.log(b.a) // x
    

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

    【讨论】:

    • 我创建了一个函数来将对象一个一个地添加到 copyData 数组中,这使得两个数组完全不同的对象但是当我再次添加调试器并循环时,我看到了 intialCountries 数组的变化每次调用 updateCurrentData 函数时(即使我在 copyData 数组上调用它)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多