JS using eval () to create variables dynamically _javascript tips

Source: Internet
Author: User

This example describes the way JS uses eval () to create variables dynamically. Share to everyone for your reference, specific as follows:

One, what is the eval () function?

The Eval_r () function computes a string and executes the JavaScript code in it.

Ii. How to define variables dynamically?

Since Eval () is able to compute a string, why not convert the definition variable to a string, and then put it into the Eval_r () function to execute, as follows:

var definestr = "var number_" +i.tostring ();
Eval_r (DEFINESTR);

This defines a variable, and you can set the debugger trace to debug to see if the number variable is defined successfully.

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

The following can be assigned a value in this form:

Eval_r ("Number_" +i.tostring () + "= 120;");

This assigns a value of 120 to its variable number_1.

But there is absolutely no way to write this:

Eval_r ("Number_" +i.tostring ()) = 120

This writing is in the wrong way.

This type of writing in IE is not workable, you need to use Executescript (string) to perform, judged as follows:

if (window.executescript)
{
//ie browser
window.executescript (DEFINESTR);
} else
{
//chrome, Firefox, etc. non ie browser
window.eval_r (DEFINESTR);
}

More about JavaScript content to view the site topics: "JavaScript Ajax Operating Skills Summary", "javascript json operation tips Summary", "JavaScript switching effects and techniques summary", " JavaScript Search Algorithm Skills Summary, "JavaScript animation effects and techniques Summary", "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and skills summary" and The summary of JavaScript mathematical operational usage

I hope this article will help you with JavaScript programming.

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.