JS:如何动态地向对象添加属性

时间:2017-02-08 17:59:18

标签: javascript

我编写了一个简单的JavaScript函数来计算数据集的平均值(参见下面的代码)。我想将结果作为新属性添加到对象本身,但它不起作用。似乎无法使用该函数的参数名称。我不明白为什么......我做错了什么?

var dataset01 = [{xdis:0,href:20.2},
  {xdis:16.5,href:18.3},
  {xdis:23.9,href:15.7},
  {xdis:36.1,href:13.4}
];

function calcAvg(ds,par){

    var total = 0;
    for(var i = 0; i < ds.length; i++) {
        total += ds[i][par];
    }
    var avg = total / ds.length;

    ds.avg[par]=avg;

 }

 calcAvg(dataset01,"href");
 calcAvg(dataset01,"xdis");

正在生成错误

Uncaught TypeError: Cannot set property 'href' of undefined
    at calcAvg ((index):26)
    at (index):30

0 个答案:

没有答案
相关问题