Eval () He is an angel and a devil

Source: Internet
Author: User

Eval literal meaning: Evaluate evaluation;

The eval function evaluates a given string containing JavaScript code and tries to execute expressions contained in the string or a series of legal JavaScript statements. The eval function uses the value or reference contained in the last expression or statement as the return value.

Example code:

VaR evalarray = ["ID", "time", "info"]; var E = eval (evalarray); console. log (E); // output: ['id', 'time', 'info']
VaR evalarray = {"ID": 1, "Time": "15:21", "info": "student"}; var E = eval (evalarray); console. log (E); // output {ID: 1, time: '15: 21', Info: 'student '}
VaR x = 2, y = 5; var E = eval ("X + Y"); console. Log (E); // output 7
Console. Log (eval ('{Timer: "Hello"}'); // output hello

The purpose of parentheses is to force the eval function to forcibly convert the expressions in parentheses into objects rather than execute them as statements when evaluating JavaScript code.

For example, object literal quantity {},

Console. Log (eval ("{}"); // output undefinedconsole. Log (eval ("({})"); // output {}

Without the outer brackets, Eval identifies the braces as the start and end marks of the JavaScript code block,

Then {} is considered to have executed an empty statement. Therefore, the following two execution results are different.

Evel accepts arbitrary strings and processes them as JavaScript code. When the problematic code is known in advance (not determined at the runtime), there is no reason to use eval (). To be precise, it is the devil!


Eval () He is an angel and a devil

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.