using for loops to swap digits

  Kiến thức lập trình

using a for loop i have to write code to swap the 2nd and 3rd digit of a number given via user input in javascript.

for ( i = 0; i < entNum.length; i++) {
if (i === 0) num2 = entNum[i];
    else if (i === entNum.length - 2) {
        newNum = newNum + num2;
        newNum = entNum[i] + newNum;
    }
else newNum = newNum + entNum[i];
}
console.log("New number:" + newNum)

this is the code i was able to produce however this code swaps the 1st and 2nd digit in the number and i can’t seems to alter the code in the way to target the 2nd and 3rd digit nor do i 100% understand for loops and if statements. so a detailed explanation would be useful.

New contributor

tamika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT