简体   繁体   English

使用JavaScript在数组外部添加值

[英]Add values outside of an array with JavaScript

I want to add the values from an array after subtracting another constant value and then squaring each value. 我想在减去另一个常量值然后平方每个值后,从数组中添加值。 I have tried the reduce method on the values, but I get an error. 我在值上尝试了reduce方法,但是我收到了一个错误。 Here is the for loop I need to use: 这是我需要使用的for循环:

 var dataset_1 = [1, 2, 3];
 var count_1 = dataset_1.length;
 var sum_1 = dataset_1.reduce(function(a,b){
 return a + b;
 }, 0  );
 var mean_1 = sum_1 / count_1;

 for(i = 0; i < count_1; i++){

  var stat_sq = Math.pow(dataset_1[i] - mean_1, 2);


  }

I need to add the values from the result of stat_sq, but the reduce method gives me this error, TypeError: stat_sq.reduce is not a function. 我需要从stat_sq的结果中添加值,但reduce方法给我这个错误,TypeError:stat_sq.reduce不是一个函数。 I think I need to somehow get the values back into an array, but I don't know how. 我想我需要以某种方式将值重新放回到数组中,但我不知道如何。

In line 2 dataset variable is not defined. 在第2行中,未定义数据集变量。 You call it dataset_1. 你称之为dataset_1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM