Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-仅将某些值传递到运行总数中_Javascript_Jquery - Fatal编程技术网

Javascript jQuery-仅将某些值传递到运行总数中

Javascript jQuery-仅将某些值传递到运行总数中,javascript,jquery,Javascript,Jquery,我有以下代码,它将20个值作为运行总数传递到变量total中: total += parseInt($(this).html(),10); 我如何才能达到相同的效果,但只针对传入的20个值中的第5、第10和第15个值 编辑: 我猜您的完整代码看起来像: $('#table1 .set2').each(function (idx) { total += parseInt($(this).html(),10); }); 您需要做的是像这样使用mod运算符: $('#table1 .set

我有以下代码,它将20个值作为运行总数传递到变量total中:

total += parseInt($(this).html(),10);
我如何才能达到相同的效果,但只针对传入的20个值中的第5、第10和第15个值

编辑:


我猜您的完整代码看起来像:

$('#table1 .set2').each(function (idx) {
    total += parseInt($(this).html(),10);
});
您需要做的是像这样使用mod运算符:

$('#table1 .set2').each(function (idx) {
    if ((idx + 1) % 5 === 0 && idx !== 19)) {
        total += parseInt($(this).html(),10);
    }
});
除20以外,每隔5个值。注意+1和19,因为它是零索引的

使用任意值执行此操作的另一种方法如下:

$('#table1 .set2').each(function (idx) {
    if ([4, 9, 14].indexOf(idx) !== -1) {//5th, 10th and 15th
        total += parseInt($(this).html(),10);
    }
});

编辑使代码更易于阅读。使用if而不是三元运算符

这是什么?为什么要删除另一个问题?$这是20个数字/值,仅此而已。元素的格式如何?这些数字是如何排列的?这是从循环内部排列的吗?这些数字是用逗号圈定的吗?你能展示你问题中的字符串吗?请欣赏,如果我需要20的任意组合,例如,1、3、8、12等,你可以在if语句中放入任何内容,例如,如果你想要1、3、8和12,你可以将if语句改为if idx==0 | | idx==2 | idx==7 | idx==11{我之所以使用mod来回答您的问题,是因为第5、第10和第15个值是5的倍数。
$('#table1 .set2').each(function (idx) {
    if ([4, 9, 14].indexOf(idx) !== -1) {//5th, 10th and 15th
        total += parseInt($(this).html(),10);
    }
});