当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。