Technical knowledge: How to use the Eval function in JavaScript __javascript

Source: Internet
Author: User

Eval function
Function: First explain the JavaScript code, and then execute it
Usage: Eval (codestring)
Codestring is a string containing JavaScript statements that are compiled using the JavaScript engine after Eval.

Example 1: Execute script with eval

var the_unevaled_answer = "2 + 3";
var the_evaled_answer = eval ("2 + 3");
Alert ("The un-evaled answer is" + The_unevaled_answer + "and the evaled answer is" + the_evaled_answer);

If you run this eval program, you will see that the string "2 + 3" in JavaScript is actually executed. So when you set the value of The_evaled_answer to eval ("2 + 3"), JavaScript will understand and return 2 and 3 and back to The_evaled_answer.
This may seem a bit silly, but it can actually do very interesting things. Like using eval, you can create a function directly from the user's input. This allows the program to change depending on the time or user input, and you can get amazing results by extrapolate.

Example 2: An object obtained through eval

Implementation: A function that asks the user which image to transform

Non-eval implementation script:

function Swapone ()
{
var the_image = prompt ("Change parrot or Cheese", "");
var the_image_object;

if (the_image = = "Parrot")
{
The_image_object = Window.document.parrot;
}
Else
{
The_image_object = Window.document.cheese;
}

THE_IMAGE_OBJECT.SRC = "Ant.gif";
}

Along with these image tags:


Script for eval implementation:

Function simpleswap ()
{
 var the_image = prompt ("Change parrot or  cheese "," ");
 var the_image_name =  "Window.document."  + the_image;
 var the_image_object = eval (the_image_name);
 the_image_object.src =  "Ant.gif";
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.