1、好奇怪的eval()
函数
1、正常情况,eval()
函数(它是全局对象的一个属性)用来解析一个表达式并计算的
2、奇怪问题一:字符串对象和字符串还是两个不一样的东西,eval()
体现得最清楚
eval("2+2"); //4
eval(new String(2+2)); //2+2
3、奇怪问题二:eval()
函数的引用直接变成全局调用
function test() {
var x = 2, y = 4;
console.log(eval('x + y')); // Direct call, uses local scope, result is 6
var geval = eval; // equivalent to calling eval in the global scope
console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined
}
4、奇怪问题三:eval()
解析字符串必须加()
才能得出想要的结果
var jsonStr = "{a:20, b:10}";
console.log(eval('('+jsonStr+')')); //{a: 20, b: 10}
5、奇怪问题四:她真的能计算
var zh_test = "你好";
var en_tesh = "hello";
var lang = "zh";
var language = lang+"_test";
console.log(language); //“zh_test”
var zh_test = "你好";
var en_tesh = "hello";
var lang = "zh";
var language = lang+"_test";
console.log(eval(language)); //"你好"