简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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