eval解惑

let a = 1,
  b = 2,
  c = 3;

let arr = [a, b, c];

function test(p1, p2, p3) {
  console.log(`${p1} ~ ${p2} ~ ${p3} ~ `);
}

test(...arr);     //1 ~ 2 ~ 3 ~
eval(`test(${arr})`);     //1 ~ 2 ~ 3 ~     这里等价于eval(`test(a,b,c)`)
test(arr);    //1,2,3 ~~~ undefined ~~~ undefined ~~~  
test(arr.toString());    //1,2,3 ~~~ undefined ~~~ undefined ~~~   这个等价于test('1,2,3')
eval('context.fn(' + args +')')    args=['arguments[1]','arguments[2]',...]
数组的展开效果与 eval 无关,是隐式类型导致的,我们来看一个例子:
console.log('1' + [1, 2, 3]) // 11,2,3

 

function fn(name) {
    console.log('my name is ' + name);
}

let name = 'hello';

eval('fn(' + 'name' + ')');  //my name is hello
eval('fn(' + name + ')'); //Uncaught ReferenceError: hello is not defined

 

posted @ 2019-07-01 15:28  little_ab  阅读(263)  评论(0编辑  收藏  举报