简体   繁体   中英

Unexpected syntax error: unexpected number

I am trying to make a function the creates a random number with decimals, but I have a syntax error using 1e+decimalPlaces .

The function is:

_$.randomNumberWithDecimals = function(min, max, decimals) {
    var random = Math.random();
    random = random * 1e+decimals;
};

and the error is on:

random = random * 1e+decimals;

the error my editor gives me is: Unexpected 1. The error I get in the google Dev Tools is: SyntaxError: Unexpected token ILLEGAL
Could someone please explain the error, and how to fix it to me?

Did you mean Math.pow(10,decimals) ?

You can't just mash together bits of code and expect it to work. When you write 1e+decimals , you might think that it will understand "stick them together like 1e5 and make it work", but it won't because it means... well, nothing really. 1e alone is not a valid number, which is why you get the error.

1e is illegal. You may want to do 1e1 , 1e2 , ... (n)e(m) . Two numbers are required around e .

You also may try Math.pow(10, decimals) or 10 ** decimals (unfortunately the latter is not supported on major browsers yet).

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