Home > Web Front-end > JS Tutorial > body text

Why add brackets to eval in JS_javascript tips

WBOY
Release: 2016-05-16 15:05:40
Original
1654 people have browsed it

eval introduction

---eval is a method of the global object prototype in the ECMA definition;

---The parameter accepted by eval is js code in string format. This string will be executed by the execution engine (remember what I said in 'Advanced Programming', create a new execution engine at this time), and then return the result to The location where eval is called.

<!DOCTYPE html>
<html>
<head>
<title>eval学习</title>
<script type="text/javascript">
/*
eval("表达式");执行表达式语句
eval("("+javascript类型+")");转为javascript对象
*/
var jsonObj={"name":"ljl","data":123};//json,是javascript的对象
var jsonString='{"name":"ljl","data":123}';//javascript的string类型,字符串内容符合json格式的样式
var objType=eval("("+jsonString+")");//通过eval函数将json字符转为javascript对象
alert( typeof jsonString);//string
alert( typeof objType);//obj
alert(eval(123));//123
alert(typeof eval("("+123+")"));//number
var x=2;
var y=eval('x+1');//执行 2+1 表达式
alert('y= '+y);//3
</script>
</head> 
<body>
</body>
</html>
Copy after login

Additional: Summary

eval is one of the dynamic features of js. It can directly execute js programs and return results. A common use is to restore json data to js objects;

However, because it can dynamically change the context object at runtime, it brings the risk of injection attacks;

When using it, pay attention to how eval understands the syntax of strings. A common problem is the 'braces' problem

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template