2017-04-17 65 views
-1

我需要用一個按鈕輸入到一個單獨的字段中求和6個值。如何檢查JS中的變量內有多少個值?

爲此,我需要知道如何檢查變量內有多少個值,以便在達到6個條目時總結這些值以便它們可以顯示在段落中。

我使用jQuery

+1

讓另一個變量,將作爲一個計數器! –

+2

你的實際代碼是怎樣的?你可以計算點擊次數,並在每次點擊時執行'++' – DaniP

+0

該字段的結構如何?你是否有分隔符?你能否提供一個例子? – DaveCoast

回答

0

推後,其他陣列中的一個所提供的所有數字和使用減少方法得到的總和。在找到總和之前,您可以使用yourArray.length來查找數字量。

0

我假設你與值的陣列的工作,如果是這樣的話:

if (values.length > 5) { 
    // disable your button 

    var i, len = values.length, total = 0; 
    for (i = 0; i < len; i++) { 

     // add up total 
     total += values[i]; 
    } 

    // display your total 
} 
0

使用$('p').each(function(a,b) {...或.find( 'P')的每個(功能(A,B)`遺囑被該段的索引號,所以增加一個檢查像

if (a < 6) { 
    ... 
} 

它意味着在多個p的比實際使用迭代,但該成本是最小的

1

試試這個

let pressCounter = 0, 
 
total = 0, 
 
inputVal = 0; 
 
$("#add").click(function() { 
 
    if(pressCounter >= 6){ 
 
     $(this).attr('disabled', 'disabled'); 
 
    }else { 
 
    pressCounter += 1; 
 
    inputVal = $("#my-input").val(); 
 
    inputVal = Number(inputVal); 
 
    total += inputVal; 
 
    console.log(total); // print total. just for test 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input id="my-input"> 
 
<input type="button" id="add" value="Add">

0

試試這個:

<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script> 
 
$(document).ready(function(){ 
 
    $("#aadd").click(function() { 
 
    var arrayy = JSON.parse("[" + $("#my-input").val() + "]"); 
 
    console.log("Length of array = "+arrayy.length) 
 
    if(arrayy.length<6 ||arrayy.length>6) 
 
    { 
 
     alert("Please enter 6 values"); 
 
    } 
 
    /*Write your logic to add 6 numbers in array*/ 
 
    }); 
 
    }); 
 
</script> 
 
</head> 
 
<body> 
 
    <input type="text" id="my-input" value="1,2,3,4,5,6"> 
 
    <input type="button" id="aadd" value="Add"> 
 
</body> 
 
</html>