Text + randomchar doesn't work [JavaScript]

2019-09-06 08:08发布

<script>
function makeid()
{
var text = "var text = document.write(lastNumber);";
var possible = "*+-/";
for( var i=0; i < 1; i++ )
document.write(lastNumber + possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
document.write(makeid(1))</script>

How do i make this to type for ex: 23* 45- 13/ and so on. What is wrong? It just show me 2 numbers and no char after.

2条回答
手持菜刀,她持情操
2楼-- · 2019-09-06 08:27
<script>
function makeid()
{
var text = document.write(lastNumber);
var possible = "*-+/";
for( var i=0; i < 1; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
document.write(makeid(1))</script>

that worked but i get "88undefined+ " what is undefinded and how do i delete it?

查看更多
甜甜的少女心
3楼-- · 2019-09-06 08:33

There are some problems with the code:

  • You haven't specified the lastNumber parameter in the function.
  • You are returning code that uses the parameter, but it's not reachable from where the code is executed.
  • The returned code uses the return value of document.write although it doesn't return anything.
  • The returned code doesn't have a script tag, so it will just be displayed on the page instead of executed.
  • You are both writing the number in the function and returning code for writing it.

Also:

  • You are using a loop that only loops once, which is pointless.

Just make the function return the string instead of returning code:

<script type="text/javascript">
function makeid(lastNumber) {
  var possible = "*+-/";
  return lastNumber + possible.charAt(Math.floor(Math.random() * possible.length));
}
document.write(makeid(1));
</script>
查看更多
登录 后发表回答