简体   繁体   English

for循环不能像我预期的那样工作

[英]for loop doesn't work as I expected

The for loop just return me 0 as cantidad value, I supposed it should have returned 2 due facturas has 2x pagado. for循环只返回0作为cantidad值,我认为应该返回2由于facturas有2x pagado。 Ty

facturas=["Mario:pagado","Vane:pagado","Velez:deuda"];

function extractNames(string){
  end=string.indexOf(":");
  return string.slice(0,end);
}

function countPaids(texto){
  count=0;
  start=texto.indexOf(":")+1;
  if(texto.slice(start,texto.length)=="pagado"){
    count++;}
    return {cantidad:count};
}

for(i=0;i<facturas.length;i++){
  factura=facturas[i];
  for(factura=0;factura<facturas.length;factura++){
    countPaids(facturas[factura]);
  }
}

Given that the other answer already solves your particular issue, I would provide some input on how to improve your code: 鉴于其他答案已经解决了您的特定问题,我将提供一些有关如何改进代码的输入:

You forgot to declare all your variables. 你忘了申报所有的变数。 When you omit the var keyword, your variables become implicit globals; 省略var关键字时,变量变为隐式全局变量; you don't want this. 你不想要这个。

I would suggest rethinking your data structure. 我建议重新考虑你的数据结构。 In JavaScript we have arrays and objects. 在JavaScript中,我们有数组和对象。 A common way to store information is in collections, which are simply arrays of objects. 存储信息的常用方法是集合,它只是对象的数组。 This will improve readability of your code, and you can easily loop collections with native JavaScript methods and your own helpers. 这将提高代码的可读性,并且您可以使用本机JavaScript方法和您自己的帮助程序轻松地循环集合。 For example: 例如:

// A collection
var facturas = [
  {name: 'Mario', state: 'pagado'},
  {name: 'Vane', state: 'pagado'},
  {name: 'Velez', state: 'deuda'}
];

// Helpers to work with collections
var dot = function(s) {
  return function(x) {
    return x[s];
  };
};

var eq = function(s) {
  return function(x) {
    return x == s;
  };
};

// Example
var states = facturas.map(dot('state')); //=> ['pagado','pagado','deuda']
var totalPaid = states.filter(eq('pagado')).length; //=> 2

You are calling a function which resets count to 0 every time. 您正在调用一个函数,每次都将count重置为0 Do your counting in your loop instead: 而是在你的循环计数:

var facturas = ["Mario:pagado","Vane:pagado","Velez:deuda"];

function extractNames(string){
    var end = string.indexOf(":");
    return string.slice(0, end);
}

/* returns true if the string contains "pagado" after the ":" */
function isPaid(texto){
    var start = texto.indexOf(":") + 1;
    return texto.slice(start,texto.length) == "pagado";
}

var count = 0;
for(var factura = 0; factura < facturas.length; factura++){
    count += isPaid(facturas[factura]);
}

// count == 2 here.

Don't forget to declare all your variables within the function scope you want to use them by using the var keyword. 不要忘记使用var关键字在要使用它们的函数范围内声明所有变量。

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

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