JavaScript - 替换对象中的数组值

时间:2017-11-28 20:54:11

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

我试图编写一个规范化数据集中特征(0到1之间)的函数。我想要迭代所有功能和替换值,因为我将它们规范化。规范化效果很好,但我无法覆盖之前的值。

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... }

以下是我的主对象中的要素数组的示例。

有关如何解决这个问题的想法吗?

谢谢!

1 个答案:

答案 0 :(得分:5)

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

修改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
}
相关问题