如何將 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

更新於: 2020 年 6 月 29 日

6K+ 檢視次數

職業生涯的新起點

完成課程獲得認證

開始吧
廣告