从起始位置(javascript)对下一个数组元素求和



我需要这个来动态使用。我有 2 个关联的数组:

Var $some = [1, 2, 3];
Var $other = [a, b, c];

a,b,c是一些HTML ID,1,2,3是它们的值。我想要触发器上这样的东西:

$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)

我在这里搜索了数组中关于查找数组中下一个元素的上一个和下一个项目,我认为循环将元素 a(然后是 b 然后 c(及其值并为每个元素执行如下代码:将下一个元素求和到它们。求和后减去元素值不会正常工作,因为我希望某些范围内的脚本发生变化......所以。。。我的问题是:如何对循环中的元素求和?我认为这将是解决这个问题的关键,因为我可以在此示例中循环它 2 次,并且会在没有启动元素的情况下停止......

如果您的someother相等,则可以尝试此解决方案。

const some = [1, 2, 3];
const other = ['a', 'b', 'c'];
other.forEach((item, index) => {
   const sum = some.reduce((s, c, i) => index !== i ? s += c : s, 0);
   
   $(`#${item}`).text(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>

我正在迭代other数组中的每个项目。传递给 forEach 的函数获得两个参数 - 当前项及其在other数组中的索引。然后我在some数组上调用reduce,并将一个函数传递给它,该函数获得三个参数 - accumulate value,当前项目及其在some数组中的索引。在正文中,我检查当前项目索引some是否不等于当前项目索引other(这可以防止a添加a的值(,所以我将其添加到s,其中包含每次迭代的结果some.reduce返回它,如果不返回结果而不添加当前项目值,则在一行语句中自动完成。

你可以像这样编写reduce函数,使其更具可读性

some.reduce((s, c, i) =>  {
   if(index !== i) {
      s += c; 
   }
   return s;
}, 0)

假设 other 的键与它在 some 上的相应值相同

const some = [1, 2, 3];
const other = [a, b, c];
$.each(other, function(key, value){                        // Loop thru each id
    var sum = some.reduce((x, y) => x + y) - some[key]; // add each 'some' elements and subtracting the id's value
    $(value).attr('max', sum);                             // set max attr of id equal to sum
});
// log output on console
console.log(a);
console.log(b);
console.log(c);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a">
<input type="number" id="b">
<input type="number" id="c">

使用 html(function) 进行循环索引和求和reduce()

var some = [1, 2, 3];
var other = ['a', 'b', 'c'];
$('#'+ other.join(',#')).html((elIdx)=>{
    return some.reduce((a,c,i) => a+= (i===elIdx ? 0 : c), 0);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>

当然,以前的解决方案效果很好,但是,以防万一,这里有更直接的解决方案:

$( "input" ).each(function( index ) {
sum=0;
for(i=0;i<$(this).siblings().length;i++) {
sum+= parseInt($( this ).siblings().eq(i).val());
}
console.log(sum);
$(this).attr('max',sum)
});

$( "input" ).each(function( index ) { // loop through each input
sum=0;
for(i=0;i<$(this).siblings().length;i++) { // get all siblings
sum+= parseInt($( this ).siblings().eq(i).val()); //calculate sum of siblings values
}
console.log(sum);
$(this).attr('max',sum)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputs">
<input type="number" id="a" value=1>
<input type="number" id="b" value=2>
<input type="number" id="c" value=3>
</div>

最新更新