3 回答

TA貢獻1811條經(jīng)驗 獲得超6個贊
這非常簡單。您可以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”類型。


TA貢獻1911條經(jīng)驗 獲得超7個贊
返回的類型new String('2 + 2')
是"object"
。
console.log( typeof new String('2 + 2') ) console.log( typeof new String('2 + 2').toString() )
由于這是一個對象,
如果 eval() 的參數(shù)不是字符串,則 eval() 返回該參數(shù)不變。
如果您使用 專門將 String 對象強制轉(zhuǎn)換為字符串基元.toString(),則它會按您的預(yù)期運行。
console.log(eval('2 + 2'));
console.log(eval(new String('2 + 2')));
console.log(eval(new String('2 + 2').toString()));
添加回答
舉報