Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Can you change an array to a number and then back to a number in Javascript?

I want to go something like this:

Start: x=789

change to an array thus now 7,8,9

then reverse it so its now 9,8,7

then make it x=987

so that 987 -0 =987

I keep getting 987-0 = NaN

2 Answers

Relevance
  • om
    Lv 6
    1 decade ago
    Favorite Answer

    You can get from the original number to an array via a string:

    x = 789 ;

    sx = new String( x ) ; // sx is a string, "789"

    ax = sx.split("") ; // ax is an array of strings, [ "7", "8", "9" ]

    rax = ax.reverse() ; // rax is an array of strings, [ "9", "8", "7" ]

    srax = rasx.join("") ; // srax is a string, "987"

    revx = new Number( srasx ) ; // revx is a number, 987

    You don't have to use explicit String and Number constructors. You can generate a string from a number by adding an empty string to the number, and you can generate a number from a string by using the string in an expression that makes it clear that you want JavaScript to treat the string as a number -- for instance, subtracting 0 from the string, or multiplying the string by 1, or dividing the string by 1. (But adding a number to the string won't work -- that will convert the number to a string and concatenate that new string onto the original string, producing a new string.)

    And of course you don't need all of those intermediate variables. You can do the whole thing in one statement if you want, like this:

    x = 789;

    revx = ( "" + x ) . split( "" ) . reverse( ) . join( "" ) - 0;

  • ?
    Lv 4
    4 years ago

    1

Still have questions? Get your answers by asking now.