如何检查JS中的变量内有多少个值?

如何检查JS中的变量内有多少个值?

问题描述:

我需要用一个按钮输入到一个单独的字段中求和6个值。如何检查JS中的变量内有多少个值?

为此,我需要知道如何检查变量内有多少个值,以便在达到6个条目时总结这些值以便它们可以显示在段落中。

我使用jQuery

+1

让另一个变量,将作为一个计数器! –

+2

你的实际代码是怎样的?你可以计算点击次数,并在每次点击时执行'++' – DaniP

+0

该字段的结构如何?你是否有分隔符?你能否提供一个例子? – DaveCoast

推后,其他阵列中的一个所提供的所有数字和使用减少方法得到的总和。在找到总和之前,您可以使用yourArray.length来查找数字量。

我假设你与值的阵列的工作,如果是这样的话:

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 
} 

使用$('p').each(function(a,b) {...或.find( 'P')的每个(功能(A,B)`遗嘱被该段的索引号,所以增加一个检查像

if (a < 6) { 
    ... 
} 

它意味着在多个p的比实际使用迭代,但该成本是最小的

试试这个

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">

试试这个:

<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>