gpt4 book ai didi

javascript - for 循环没有按我的预期工作

转载 作者:行者123 更新时间:2023-12-02 17:53:40 25 4
gpt4 key购买 nike

for 循环只返回 0 作为候选值,我认为它应该返回 2,因为事实有 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 中,我们有数组和对象。存储信息的常见方法是集合,即简单的对象数组。这将提高代码的可读性,并且您可以使用 native 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com