Text + randomchar doesn't work [JavaScript]

时光总嘲笑我的痴心妄想 提交于 2019-12-25 00:50:16

问题


<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.


回答1:


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>



回答2:


<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?



来源:https://stackoverflow.com/questions/4572026/text-randomchar-doesnt-work-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!