JS uses eval () to dynamically create variables, jseval

Source: Internet
Author: User

JS uses eval () to dynamically create variables, jseval

This article describes how JS uses eval () to dynamically create variables. We will share this with you for your reference. The details are as follows:

1. What is the eval () function?

The eval_r () function computes a string and executes the JavaScript code.

2. How to dynamically define variables?

Since eval () can calculate a string, why not convert the syntax of the defined variable to a string and then put it into the eval_r () function for execution, as shown in:

Var defineStr = "var number _" + I. toString (); eval_r (defineStr );

In this way, a variable is defined. You can set the debugger to trace and debug the variable to see if the number variable is successfully defined.

If the I value is 1, the dynamic variable is number_1.

In the future, you can assign values to them in this form:

Eval_r ("number _" + I. toString () + "= 120 ;");

In this way, the variable number_1 is assigned 120.

However, it is absolutely impossible to write as follows:

Eval_r ("number _" + I. toString () = 120

This write method is incorrect.

The preceding method does not work in IE. You need to use executeScript (string) to execute it. The judgment is as follows:

If(window.exe cuteScript) {// ieviewer window.exe cuteScript (defineStr);} else {// non-ie browsers such as Chrome and Firefox window. eval_r (defineStr );}

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.