當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Javascript eval()用法及代碼示例



eval()是全局對象的函數屬性。

  • eval()函數的參數為​​字符串。
  • 如果字符串表示一個表達式,則eval()評估該表達式。如果參數代表一個或多個JavaScript語句,則eval()將評估這些語句。
  • 我們不調用eval()來評估算術表達式; JavaScript自動評估算術表達式。

用法:

eval(string)
參數:
String:
A string representing a JavaScript expression, statement, or 
sequence of statements. The expression can include variables 
and properties of existing objects.

返回值:
The completion value of evaluating the given code is 
returned by using eval(). 
If the completion value is empty, undefined is returned. 

例子:


Input:eval(new String('2 + 2'));
Output:returns a String object containing "2 + 2"

Input:eval(new String('4 + 4'));
Output:returns a String object containing "4 + 4"

下麵的程序將說明eval()的用法:函數更深入:程序1:

<script> 
    // JavaScript to illustrate eval() function 
    function func() { 
  
        // Original string 
        var a = 2; 
        var b = 2; 
  
        // Finding the sum 
        var value = eval(new String(a + b)); 
        document.write(value); 
    } 
// Driver Code 
func(); 
< /script>                    

輸出:

4

程序2:

<script> 
    // JavaScript to illustrate eval() function 
    function func() { 
  
        // Original string 
        var a = 4; 
        var b = 4; 
  
        // Finding the multiplication 
        var value = eval(new String(a * b)); 
        document.write(value); 
    } 
// Driver code 
func(); 
< /script>                    

輸出:

16


相關用法


注:本文由純淨天空篩選整理自Shubham_Singh_29大神的英文原創作品 Javascript | eval() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。