简体   繁体   中英

How to use a function as a string?

I'm trying to use a function as a string right now and it doesn't seem that it's possible. To give you an example of what I mean take a look at the file below:


<!DOCTYPE html>
<html>
<title>Test Webpage</title>
<div id = "storyDisplay"></div>
<script>
var story = [];
var dangerElements = ["test1","test2","test3"];
function danger () {
    story.push(dangerElements[Math.round(Math.random()*dangerElements.length)];
    document.getElementById("storyDisplay").innerHTML = story.join("");
}

</script>
</html>

Now when I try to input this code it comes out as:



Basically, there's no output. I checked the file and it doesn't seem like there's a syntax error, so what's happening?

[EDIT] Sorry, whoops, forgot to add in this part. I want to use danger() like this:

 var genStory = [danger()]; 

and I want it to output as a random string in story.

你只是错过了第9行的方括号和右括号

story.push(dangerElements[Math.round(Math.random()*dangerElements.length)]);

Is this what you are after?

 var genStory = [(danger)()]; alert( genStory ); 
 <!DOCTYPE html> <html> <title>Test Webpage</title> <div id = "storyDisplay"></div> <script> var story = []; var dangerElements = ["test1","test2","test3"]; function danger () { story.push(dangerElements[Math.round(Math.random()*dangerElements.length)]); return document.getElementById("storyDisplay").innerHTML = story.join(""); } </script> </html> 

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