在 JS 中减去列中的值 [英] Subtract values in column in JS

查看:29
本文介绍了在 JS 中减去列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个 cvs 文件,其中一列包含 unix 时间戳.我想计算 value1 和 value2、value 2 和 value3 等之间的差异.我该怎么做?

I am reading a cvs-file and one column contains unix timestamps. I would like to calculate the difference between value1 and value2, value 2 and value3 et cetera. How should I do this?

推荐答案

阅读评论后编辑的代码片段.似乎数据中的所有差异都是 900 毫秒,但此代码应该适用于任何其他值.

Edited code snippet after reading comments. It seems that all differences in the data are 900 mSec, but this code should work for whatever other values.

需要注意的是,它假设数据中似乎存在从高到低"的排序.

Thing to note is that it assumes "high to low" ordering as seemingly present in the data.

var csv = [
  '1374225300,126.0,1662.0,379.0,337.0,1091.0,893.0',
  '1374224400,84.0,1491.0,251.0,289.0,909.0,801.0',
  '1374223500,72.0,1200.0,126.0,180.0,651.0,682.0 ',
  '1374222600,84.0,1011.0,126.0,180.0,505.0,563.0 ',
  '1374221700,72.0,718.0,84.0,109.0,295.0,441.0 '
  //... etcetera
];

function getPairDifference( pair ) {
  //"pair" is a zero-based integer.
  // "0" will return a difference between csv rows "0" & "1"
  // "1" will return a difference between csv rows "1" & "2"
  // etcetera...

  var firstVal = parseInt( csv[pair].split(",")[0] );
  var secondVal = parseInt( csv[pair + 1].split(",")[0] );
  return firstVal - secondVal;
}

for ( var i = 0; i < csv.length; i += 1) {
  // Demo code to visualize numbers.
  // Actual function call of interest is simply "getPairDifference( i )"
  $( "<div></div>" ).text( "DIFF "+i+": " + getPairDifference( i ) ).appendTo( "body" );
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于在 JS 中减去列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆