[英]Sum next array elements from a starting position (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)的元素的值並為每個元素執行一個代碼,例如:sum next元素。 求和后減去元素值將無法正常工作,因為我希望該腳本在某些范圍內發生變化...所以...我的問題是:如何求和從循環中迭代的元素? 我認為這將是解決此問題的關鍵,因為在此示例中我可以將其循環2次,並且在沒有開始元素的情況下會停止...
如果您的some
與other
人相等,則可以嘗試此解決方案。
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
如果沒有返回結果而不添加當前項目值,則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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.