[JavaScript] Interesting eval

String calculation

  1. let num = eval("1+1") => 2
  2. let num = eval("x=10;y=20;x*y") => 200

JSON conversion

  • Function defined as a string requires "(" and ")" as prefix and suffix
  • Example:
var fctStr1 = 'function a() {}'
var fctStr2 = '(function a() {})'
var fct1 = eval(fctStr1)  // 返回undefined
var fct2 = eval(fctStr2)  // 返回一个函数
  • Example:
    let num = eval("("+ "{'name':'zhangsan', age:20}" +")")=> {name:'zhangsan', age: 20}


but! Just have fun! Never use eval in a formal environment!

eval() is a dangerous function, it executes code with the same permissions as the caller. If the string code you run with eval() is modified by a malicious party (innocent person), you may end up running malicious code on the user's computer under the authority of your webpage/extension. More importantly, third-party code can see the scope of a certain eval() when it is called, which may also lead to some attacks in different ways

Guess you like

Origin blog.csdn.net/m0_46537958/article/details/108534977