简体   繁体   English

JavaScript整数数组错误

[英]Javascript Integer Array Error

I'm making a function that takes in user input and must display it as 7 characters ie if 42.54 was entered it would display 0004254. My issue is that I'm taking an integer and applying it to an array causing an undefined error when applying the 0's 我正在制作一个接受用户输入的函数,并且必须将其显示为7个字符,即如果输入42.54,它将显示0004254。我的问题是我正在获取一个整数并将其应用于数组,导致在应用时导致未定义的错误0的

function BackDataDefaultInput() {
// Balance
    var count;
    var newNum = "";
    var balanceText = document.getElementById('balanceNumBox').value;
    count = balanceText.length;

while (count > 0 && count < 7) {
    newNum += '0';
    count++
}
var formattedBalance = parseInt(balanceText, 10) * 100;
for (var i = 0; i < balanceText.length; i++) {
    formattedBalance[i] = new Array();
    // Error here showing as undefined for formattedBalance[i]
     newNum += formattedBalance[i];
}

This code worked before I had to multiply it by 100 to get the right format. 在我必须将其乘以100以获得正确的格式之前,此代码有效。 as I was just appending two strings. 因为我只是追加两个字符串。 Can somebody help me think of a solution? 有人可以帮我想办法吗?

Primitives (like numbers) are immutable; 基元(如数字)是不可变的; if you have 如果你有

var formattedBalance = parseInt(balanceText, 10) * 100;

you can't proceed to reassign index properties like 您无法继续重新分配索引属性,例如

formattedBalance[i] = new Array();

It would probably be easier to remove the (possible) period with a regex and use padStart rather than mess with arrays: 使用正则表达式删除(可能的)句点并使用padStart比将数组弄乱更容易:

 function BackDataDefaultInput() { const balanceText = '42.54'; // document.getElementById('balanceNumBox').value; console.log( balanceText .replace(/\\./g, '') .padStart(7, '0') ); } BackDataDefaultInput(); 

Try to use following function. 尝试使用以下功能。

 var balanceText = "42.54"; //document.getElementById('balanceNumBox').value; var formattedBalance = balanceText * 100; function formatInteger(str, max) { str = str.toString(); return str.length < max ? formatInteger("0" + str, max) : str; } console.log(formatInteger(formattedBalance, 7)); 

Answer to my question in case it helps anyone that comes across this page: 如果有问题,请回答我的问题:

function BackDataDefaultInput() {
    var balanceText = document.getElementById('balanceNumBox').value;
    var balance = parseFloat(balanceText) * 100;
    balanceText = String(balance);

while (balanceText.length > 0 && balanceText.length < 7) {
    balanceText = '0' + balanceText;
    }
}

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

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