Javascript uses eval or new Function for syntax check

Source: Internet
Author: User

Use new Function () for syntax check
The eval () method cannot be used in disorder. Using the eval () method when not appropriate may cause problems in the entire program;
And new Function () is not that big a problem. Although the new Function () works directly in the global scope under any circumstances, if it only performs syntax checks, it will not generate unexpected results due to scope issues, as long as you do not directly call the new function constructed through it.

Add "0," Before the parameter accepted by eval ,"
In fact, this is because there is a bug in IE. For some reason, if you want to dynamically construct a function in IE by calling eval.
For example:
Eval ('(function () {/* code here */})');
The returned result in IE will be undefined, while other browsers will return the reference of the newly constructed function correctly.
The simplest and most effective solution is to add "0," to the front to be compatible with all mainstream browsers.
For example:
Eval ('0, function () {/* code here */}');
Note: In the Chakra engine of IE9, this problem has been solved.

Use the concat method of the array object to generate a new array
Convert a single object parameter to an array containing only one element before processing. You can use the []. concat (o) format.
For example:Copy codeThe Code is as follows: var arr1 = [1, 2];
Var arr2 = [3, 4];
Var arr3 = arr1.concat (arr2 );
Alert (arr3.length );

Another method is: if (! (O instanceof Array) o = [o];
// It is less rigorous than isArray in ECMAScript 5.

Reply:
1. eval cannot be used in disorder;
2. in IE eval, my solution is to execute return in the function body;
3. Array. prototype. concat. apply ([1, 2, 3], [4, 5, 6]);

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.