如何將 JavaScript 中的字串轉換成函式?
要將字串轉換成函式,應使用“eval()”方法。此方法將一個**字串**作為引數並將其轉換成函式。
語法
eval(string);
示例
在以下示例中,在字串本身中,將名為 'age' 的屬性分配給一個函式。然後,使用 eval() 函式將 age 屬性轉換成函式,並如輸出所示進行顯示。
<html> <body> <script> var string = '{"name":"Ram", "age":"function() {return 27;}", "city":"New jersey"}'; var fun = JSON.parse(string); fun.age = eval("(" + fun.age + ")"); document.write(fun.name + " "+ "of Age" + " "+ fun.age()+ " " + "from city" +" "+ fun.city); </script> </body> </html>
輸出
Ram of Age 27 from city New jersey
廣告