为了账号安全,请及时绑定邮箱和手机立即绑定

javascript eval() 函数的参数

javascript eval() 函数的参数

德玛西亚99 2023-09-28 10:19:04
我很想在MDN上阅读有关 eval() 函数的更多信息,并遇到了以下段落如果 eval() 的参数不是字符串,则 eval() 返回该参数不变。在以下示例中,指定了 String 构造函数,并且 eval() 返回 String 对象而不是计算字符串。eval(new String('2 + 2')); // returns a String object containing "2 + 2" eval('2 + 2');             // returns 4这对我来说没有意义,因为“如果 eval 不评估它的参数,如果它不是字符串,那么它为什么要创建一个新的对象实例!?”
查看完整描述

3 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

这非常简单。您可以eval如下剖析:


if (typeof argument === "string") return <evaluation of string>;

else return argument; // eval just returns what it gets

所以你的例子:


    eval(new String('2 + 2'));

您可以将其分为两个语句:


let arg = new String('2 + 2');

console.log(typeof arg); // object

console.log(eval(arg) === arg); // true, because typeof arg is not "string"


另外两个示例将类型字符串传递给eval:


let arg = "new String(2+2)";

console.log(typeof arg); // string

// Now we get evaluation of 2+2 and String constructor is called:

console.log(eval(arg)); // a String object (that's what the constructor produces)

'2 + 2'在第三个示例中,计算字符串,即字符串“2 + 2”。其余与第二个例子相同。

请注意,String 对象不是 string”类型,而是“object”类型。


查看完整回答
反对 回复 2023-09-28
?
大话西游666

TA贡献1817条经验 获得超14个赞

你的例子就可以正常工作。

第一个 eval 的参数是一个对象,而不是原始变量。

eval(new String('2 + 2')); // So eval doesn't do anything here and return argument without any operation.

第二个 eval( 的参数是一个纯字符串。无论里面是什么,eval 都会直接作为 JavaScript 代码执行。

eval("new String(2+2)") // This will first calculate 2 + 2 and create a new string object with argument 4.

最后一个,它是一个字符串,因此 eval 将直接将其作为 JavaScript 代码执行,如第二个示例所示。不同之处在于,String 对象现在接受字符串 '2 + 2'

eval("new String('2 + 2')"); // returns a string object with a string argument.

希望这个解释有帮助。


查看完整回答
反对 回复 2023-09-28
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

返回的类型new String('2 + 2')"object"

console.log( typeof new String('2 + 2') )
console.log( typeof new String('2 + 2').toString() )

由于这是一个对象,


如果 eval() 的参数不是字符串,则 eval() 返回该参数不变。


如果您使用 专门将 String 对象强制转换为字符串基元.toString(),则它会按您的预期运行。


console.log(eval('2 + 2'));   

console.log(eval(new String('2 + 2')));

console.log(eval(new String('2 + 2').toString()));


查看完整回答
反对 回复 2023-09-28
  • 3 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信