将数学应用于数组中的值

时间:2014-04-23 11:13:29

标签: javascript arrays

我有一个数组:

var myarray = ["5,35.0", "15,45.0", "25,45.0", "35,50.0", "45,60.0", "55,65.0", "65,60.0", "75,60.0", "85,70.0", "95,80.0"]

值对应于图表上的x,y点。

我需要对每个y值应用数学来改变y轴刻度。为了简单起见,假设我需要将每个y值乘以2.

我该怎么做?

3 个答案:

答案 0 :(得分:4)

使用map循环数组,将字符串转换为一对数字,执行添加以确保小数位保持不变。

var out = myarray.map(function (el) {
  var xy = el.split(',').map(Number);
  xy[1] = (xy[1] * 2).toFixed(1);
  return xy.join(',');
});

Fiddle

答案 1 :(得分:3)

您需要遍历每个元素并通过','分割它们。然后对它做MATH并将其保存回来。

说,

for(var i=0;i<myarray.length;i++){
    var temp = (parseFloat(myarray[i].split(',')[1])).toFixed(2);
    temp = temp * 2; 
    myarray[i] = myarray[i].split(',')[0] + "," + temp;
}

答案 2 :(得分:1)

粗略地说,

var myarray = ["5,35.0", "15,45.0", "25,45.0", "35,50.0", "45,60.0", "55,65.0", "65,60.0", "75,60.0", "85,70.0", "95,80.0"];

var y = 0;
var x = 0;

for(var i in myarray) {
    y = parseFloat(myarray[i].split(",")[1]);
    x = parseFloat(myarray[i].split(",")[0]);
    y = y * 2; // or your operation
    myarray[i] = x + "," + y;
}

console.log(myarray);

HTH