eval()

程序語言中的函數

eval()是程序語言中的函數,功能是獲取返回值,不同語言大同小異,函數原型是返回值 = eval( codeString ),如果eval函數在執行時遇到錯誤,則拋出異常給調用者。

JavaScript


函數功能

eval() 函數可將字元串轉換為代碼執行,並返回一個或多個值

函數原型

返回值 = eval( codeString )

函數說明

如果eval函數在執行時遇到錯誤,則拋出異常給調用者.
類似的函數是loadcode ,loadcode並不立即執行代碼,而是返回一個函數對象.
並且loadcode支持路徑參數,eval並不支持. eval並不支持代碼中的return語句,而是將代碼作為表達式直接計算出結果.

實例

var d = eval("({name:'chentong'})")
alert(d.name);

Matlab


Function

Execute string containing MATLAB expression

Syntax

eval(expression)
[a1, a2, a3, ...] = eval('myfun(b1, b2, b3, ...)')

Description

eval(expression) executes expression, a string containing any valid MATLAB expression. You can construct expression by concatenating substrings and variables inside square brackets:
expression = [string1, int2str(var), string2, ...]
[a1, a2, a3, ...] = eval('myfun(b1, b2, b3, ...)') executes function smyfun with arguments b1, b2, b3, ..., and returns the results in the specified output variables.

Remarks

Using the eval output argument list is recommended over including the output arguments in the expression string. The first syntax below avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior. Use the second syntax instead:
% Not recommended
eval('[a1, a2, a3, ...] = function(var)')
% Recommended syntax
[a1, a2, a3, ...] = eval('function(var)')

Examples

Example 1 – Working with a Series of Files
Load MAT-files August1.mat to August10.mat into the MATLAB workspace:
for d=1:10
s = ['load August' int2str(d) '.mat']
eval(s)
end
These are the strings being evaluated:
s =
load August1.mat
s =
load August2.mat
s =
load August3.mat
- etc. -
Example 2 – Assigning to Variables with Generated Names
Generate variable names that are unique in the MATLAB workspace and assign a value to each using eval:
for k = 1:5
t = clock;
pause(uint8(rand * 10));
v = genvarname('time_elapsed', who);
eval([v ' = etime(clock,t)'])
end
As this code runs, eval creates a unique statement for each assignment:
time_elapsed =
5.0070
time_elapsed1 =
2.0030
time_elapsed2 =
7.0010
time_elapsed3 =
8.0010
time_elapsed4 =
3.0040
Example 3 – Evaluating a Returned Function Name
The following command removes a figure by evaluating its CloseRequestFcn property as returned by get.
eval(get(h,'CloseRequestFcn'))

PHP


函數功能

Eval函數在PHP代碼中的使用:eval() 函數把字元串按照 PHP 代碼來計算。該字元串必須是合法的 PHP 代碼,且必須以分號結尾。如果沒有在代碼字元串中調用 return 語句,則返回 NULL。如果代碼中存在解析錯誤,則 eval() 函數返回 false。實例如圖所示。

實例

VBScript


函數功能

Eval函數在VBScript腳本語言中的使用:在VB腳本語言中,Eval函數具有兩層意思,一是實現計算表達的值,即eval()函數可將字元串轉換為代碼執行,並返回一個或多個值;二是運行指定的代碼。

實例

Python


函數功能

eval通常用來執行一個字元串表達式,並返回表達式的值。

語法

eval(expression[, globals[, locals]])
有三個參數,表達式字元串,globals變數作用域,locals變數作用域。其中第二個和第三個參數是可選的。
如果忽略後面兩個參數,則eval在當前作用域執行。

實例

如果指定globals參數
如果指定locals參數
如果要嚴格限制eval執行,可以設置globals為__builtins__,這樣 這個表達式只可以訪問__builtin__module。