简体   繁体   English

如何计算 javascript 中带前导零的数字的位数?

[英]How can I count the number of digits of a number with leading zeros in javascript?

I am taking a field value, that should be a 4 digit number.我正在获取一个字段值,它应该是一个 4 位数字。

I want to make sure that the value is a 4 digit number and if not, have a pop up that says "enter a 4 digit number".我想确保该值是 4 位数字,如果不是,则弹出“输入 4 位数字”。

I noticed that when I put the field value into a variable it does not take any of the leading zeros.我注意到,当我将字段值放入变量中时,它不会使用任何前导零。 The last test case I ran the code with was a value of '0000'.我运行代码的最后一个测试用例是值“0000”。

var relay = this.getField("RELAY NUM").value;
var relayString = relay.toString();
var relaySplit = relayString.split("");
    
console.println("relay= " + relay);
console.println("string= " + relayString);
console.println("split= " + relaySplit);
    
for(i = 0; i < 4; i++){
    if (relaySplit[i] >= 0) {
        console.println("Looks good so far");
    } else {
        console.println("Please enter 4 digit number");
    }
}

--------------------------------------------------------
relay= 0
string= 0
split= 0
Looks good so far
Please enter 4 digit number
Please enter 4 digit number
Please enter 4 digit number

true

Instead of traversing arrays, an approach you may want to consider is using a regex to determine whether the input value meets your criteria.除了遍历 arrays,您可能需要考虑的一种方法是使用正则表达式来确定输入值是否符合您的标准。 Then on events such as keyup (using jQuery here but not necessary), you run the validation and apply styles, or send forth the popups as you wish.然后在诸如 keyup 之类的事件上(在此处使用 jQuery 但不是必需的),您运行验证并应用 styles,或根据需要发送弹出窗口。 I put a limit on the length of the input so users are not able to enter MORE then expected input, but this isn't necessarily needed.我对输入的长度进行了限制,因此用户无法输入比预期输入更多的输入,但这并不是必需的。

 $("#input").keyup(function() { let input = $("#input").val() let isValid = validate(input) $("#val").text(isValid? "Valid": "Invalid") }) function validate(val) { let x = /^[0-9]{4}$/ return x.test(val) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input type="text" id="input" maxLength="4" /> <label id="val"></label> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM