for循环仅将0作为我的候选值返回给我,我认为它应该已返回2由于facturas具有2x pagado。泰

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]);
  }
}

最佳答案

鉴于其他答案已经解决了您的特定问题,我将提供一些有关如何改进代码的意见:

您忘记声明所有变量。当您省略var关键字时,变量将成为隐式全局变量。你不要这个

我建议重新考虑您的数据结构。在JavaScript中,我们有数组和对象。存储信息的一种常见方式是在集合中,集合只是对象的数组。这将提高代码的可读性,并且您可以轻松地使用本机JavaScript方法和您自己的助手循环收集。例如:

// 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

关于javascript - for循环无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21151370/

10-12 12:30
查看更多