简体   繁体   中英

How to convert number string in an array to number in JavaScript?

I want to use Fisher Yates shuffle algorithm to shuffle each integer from Math.random() after the ". (dot)". I split them into string and use the Fisher Yates shuffle algorithm but I am stuck on how to convert it back to number.

From: ["0", ".", "4", "1", "2", "7", "2", "9", "5", "8", "6", "7", "0", "7", "4", "2", "8", "1"]

To: 0.4127295867074281

    var randomNum = Math.random();
    var stringNum = randomNum.toString();
    var stringArray = stringNum.split("");

    var i = stringArray;
    var j;
    var temp;

    while (--i > 1) {
        j = Math.floor(Math.random() * (i + 1));
        temp = stringArray[j];
        stringArray[j] = stringArray[i];
        stringArray[i] = temp;
    }
var str = "42";
var num = str * 1;

For the full number:

var fullNum = stringArray.join("") * 1

First join the array and then cast to number Number(strArray.join(""))

 var strArray = ["0", ".", "4", "1", "2", "7", "2", "9", "5", "8", "6", "7", "0", "7", "4", "2", "8", "1"]; var num = Number(strArray.join("")); // this prints 0.4127295867074281 document.write(num); 

I'm amazing with logic, but not so much with each language but here is a basic, idea in logic. Remember below I am concatenating

x = 0 y = 0

while( y > 10)

z = generate random number greater that 0 and less than 10;

x = "x" + "." + "z"

end

answer = x

answer = answer + x

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