【问题标题】:JavaScript - Replacing array value within objectJavaScript - 替换对象内的数组值
【发布时间】:2018-05-12 10:50:12
【问题描述】:

我正在尝试编写一个函数来规范化数据集中的特征(0 到 1 之间)。我想在规范化它们时遍历所有功能和 replace 值。规范化效果很好,但我无法覆盖之前的值。

Data.prototype.normalize = function(dataset) {

    // Get the extent for each feature
    for (var feature = 0; feature < this.featureCount; feature++) {
        var extent = this.getExtent(feature, dataset),
            min    = extent[0],
            max    = extent[1];

        // uses extent to normalize feature for all companies
        for (var company = 0; company < this.companies.length; company++) {
            var value      = this.companies[company][dataset][feature],
                normalized = this.normalizeValue(value, min, max);

            value = normalized;
        }
    }

}

一切都失败了

value = normalized;

如果我在覆盖它之后使用 console.log(value),一切似乎都可以正常工作,但仅限于函数范围内。在这个范围之外,原始值仍然存在。

data.companies[n] = { features : [1, 2, 3, 4, 5], other properties... }

这是我的主要对象中的特征数组的示例。

关于如何解决此问题的任何想法?

谢谢!

【问题讨论】:

标签: javascript arrays object pass-by-reference overwrite


【解决方案1】:

为了使更改反映在您的对象而不是函数中,您需要显式设置对象的属性。

修改您的 for 循环以显式设置标准化值,如下所示:

for (var company = 0; company < this.companies.length; company++) {
    var value      = this.companies[company][dataset][feature],
        normalized = this.normalizeValue(value, min, max);

    this.companies[company][dataset][feature] = normalized; // explicitly set value
}

【讨论】:

  • 不错的通灵调试。
猜你喜欢
  • 2015-03-31
  • 1970-01-01
  • 2014-08-20
  • 2020-05-23
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 2020-01-16
相关资源
最近更新 更多