Search code examples
javascriptarraysloopsfor-loopsuperscript

Make integer in For Loop Superscript


Okay, so obviously you can't make an integer a superscript since it's a number. I need you guys. How would I take the integer from the loop and make it into a string so I can .sup() it. I'm open to using an array.

Here is the original

var n;
for (let i = 0; i <= 31; i++) {
  n = Math.pow(2, i);
  document.write("2 ^ " + i + " = " + n + "<br>");
}  

Here is with an array (NOT FUNCTIONING!)

var n, myArray = [];
for (let i = 0; i <= 31; i++) {
  myArray.push(Math.pow(2, i));
}

for (var j = 0; j <= 31; j++) {
  document.write("2" + myArray[j].sup() + " = " + n + "<br />");
}

Thoughts?


Solution

  • sup is a method on String. So, you have to convert the number to a String first:

    myArray[j].toString().sup()
    

    Note: in many cases anything is converted to String implicitly, but not when you call a method on an object.

    var n, myArray = [];
    for (let i = 0; i <= 31; i++) {
      myArray.push(Math.pow(2, i));
    }
    
    for (var j = 0; j <= 31; j++) {
      document.write("2" + myArray[j].toString().sup() + " = " + n + "<br />");
    }