【问题标题】:Finding totals of certain strings in an Array查找数组中某些字符串的总数
【发布时间】:2016-11-10 14:57:01
【问题描述】:

我有两个数组,一个包含税码 (emptaxdeductcode),另一个包含为这些税码支付的金额 (emptaxamt)。

我正在尝试查找为仅以 31 结尾的税码支付的金额。这些税码的字符数不同,但我需要的总是 12 个字符。

尝试使用简单的 for 循环,但它似乎在第 3 行中断。即使对于那些有相关税码的人,它也始终显示 0:

var returnedValue = 0;
for (var q = 0; q < emptaxdeductcode.length; q++) {
    if (emptaxdeductcode[q].substring(10,11) == "31") {
        returnedValue += emptaxamt[q];
    } else {
        0;
    }
}
returnedValue;

我已经尝试了以下作为测试,它返回 true: (此税码并不总是在 [5] 中,所以我不能只使用它。另外,有些人有多个以 31 结尾的税码)

if (emptaxdeductcode[5].substring(10,11) == "31") {
    "TRUE";
} else {
    "FALSE";
}

因此,引起问题的一定是 for 循环中的子字符串。任何指导将不胜感激!

编辑:这是数据示例。抱歉,如果这导出奇怪 - 不完全确定如何制作表格:

emptaxdeductcode |杀虫剂

--- | ---

00-10 | 55.36

00-11 | 8.33

00-12 | 35.63

39-20 | 17.64

39-22 | 0.40

390770040-31 | 9.48

390770040-32 | 2.00

Edit2:我用来构建此报告的这个软件不支持许多 JS 实用程序/库。 stackoverflow 上很多与我有类似问题的帖子都已通过“原型”函数或 AngularJS 之类的东西得到解决。不幸的是,这对我不起作用。

【问题讨论】:

  • 如何在第 3 行中断?
  • 在处理它之前尝试记录 emptaxdeductcode[q] 的值,看看它在错误之前是什么。 emptaxdeductcode 可以包含任何空值吗?
  • 你能展示一下你的数据是什么样子的吗?
  • @epascarello - 打破,我的意思是它只是没有给我我需要的数据。它总是在不应该的时候返回零。
  • @TheReason 我编辑了我的帖子以显示一名员工的数据样本。

标签: javascript arrays for-loop subtotal


【解决方案1】:

我认为您的主要问题是您只使用子字符串而不是 2 从字符串中读取 1 个字符。

我想你想要

emptaxdeductcode[q].substring(10,12)

改为。

这是一些示例代码和一个 JSFiddle。

var emptaxdeductcode = ["123451234531", "123451234532"];
var emptaxamt = [10, 20];

var returnedValue = 0;
for (var q = 0; q < emptaxdeductcode.length; q++)
{
    if (emptaxdeductcode[q].substring(10,12) == "31") {
        returnedValue += emptaxamt[q];
    } else {
        0;
    }
}
alert(returnedValue);

JSFiddle Code

【讨论】:

  • 谢谢克里斯。我去尝试了这个 - 不幸的是没有bueno。即使将其更改为 substring(10) 也不起作用。
  • 很奇怪。它在 jsFiddle 中完美运行。尝试将其输出记录到应用程序的控制台中。 console.log(emptaxdeductcode[q].substring(10,12));告诉我们你得到了什么。
【解决方案2】:

当你这样做时

console.log(emptaxdeductcode[q].substring(10, 11));

您会看到返回的是3,而不是31。所以你需要把它提高到 12。

var emptaxdeductcode = ["00-10", "00-11", "00-12", "39-20", "39-22", "390770040-31", "390770040-32"],
  emptaxamt = [55.36, 8.33, 35.63, 17.64, 0.40, 9.48, 2.00];

var returnedValue = 0;
for (var q = 0; q < emptaxdeductcode.length; q++) {
  if (emptaxdeductcode[q].substring(10, 12) == "31") {
    returnedValue += emptaxamt[q]
  }
}

console.log(returnedValue);

我个人会使用

var code = emptaxdeductcode[q].substr(-2);

var code = emptaxdeductcode[q].split("-").pop();

var emptaxdeductcode = ["00-10", "00-11", "00-12", "39-20", "39-22", "390770040-31", "390770040-32"],
  emptaxamt = [55.36, 8.33, 35.63, 17.64, 0.40, 9.48, 2.00];


var total = emptaxdeductcode.reduce( function(total, code, ind){
    if (code.split("-").pop() === "31") {
      total += emptaxamt[ind];  
    }
    return total;
}, 0);

console.log(total);

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2014-11-19
    • 2019-11-13
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多