Share via


使用者定義的 JScript 函式

更新:2007 年 11 月

雖然 JScript 包括許多內建的函式,您仍然可以建立自己的函式。函式定義是由一個函式陳述式和一個 JScript 陳述式的區塊所組成。

定義自己的函式

下列範例中的 checkTriplet 函式會用三角形的邊長來做為它的引數。它會從這些數字計算該三角形是否為直角三角形,只要檢查三個數字是否組成一個畢氏三分析元 (直角三角形斜邊長度的平方等於另外兩個邊長度的平方和) 即可。為了進行實際測試,checkTriplet 函式會呼叫兩個其他函式中的其中一個。

請注意,在浮點版本的測試中,會使用很小的數字 (epsilon) 做為測試變數。因為浮點計算中的不確定性和捨入誤差,所以除非已經知道討論中的三個值皆為整數,不然直接測試三個數字是否構成畢氏三分析元並不實際。因為直接測試較為正確,所以這個範例中的程式碼會判斷它是否適當,如果適當的話就用它。

定義這些函式時,不會使用型別附註。在此應用中,讓 checkTriplet 函式同時接受整數和浮點資料型別很有幫助。

const epsilon = 0.00000000001; // Some very small number to test against.

// Type annotate the function parameters and return type.
function integerCheck(a : int, b : int, c : int) : boolean {
   // The test function for integers.
   // Return true if a Pythagorean triplet.
   return ( ((a*a) + (b*b)) == (c*c) );
} // End of the integer checking function.

function floatCheck(a : double, b : double, c : double) : boolean {
   // The test function for floating-point numbers.
   // delta should be zero for a Pythagorean triplet.
   var delta = Math.abs( ((a*a) + (b*b) - (c*c)) * 100 / (c*c));
   // Return true if a Pythagorean triplet (if delta is small enough).
   return (delta < epsilon);
} // End of the floating-poing check function.

// Type annotation is not used for parameters here. This allows 
// the function to accept both integer and floating-point values 
// without coercing either type.
function checkTriplet(a, b, c) : boolean { 
   // The main triplet checker function.
   // First, move the longest side to position c.
   var d = 0; // Create a temporary variable for swapping values
   if (b > c) { // Swap b and c.
      d = c;
      c = b;
      b = d;
   }
   if (a > c) { // Swap a and c.
      d = c;
      c = a;
      a = d;
   }

   // Test all 3 values. Are they integers?
   if ((int(a) == a) && (int(b) == b) && (int(c) == c)) { // If so, use the precise check.
      return integerCheck(a, b, c); 
   } else { // If not, get as close as is reasonably possible.
      return floatCheck(a, b, c); 
   }
} // End of the triplet check function.

// Test the function with several triplets and print the results.
// Call with a Pythagorean triplet of integers.
print(checkTriplet(3,4,5));
// Call with a Pythagorean triplet of floating-point numbers.
print(checkTriplet(5.0,Math.sqrt(50.0),5.0));
// Call with three integers that do not form a Pythagorean triplet.
print(checkTriplet(5,5,5));

本程式的輸出為:

true
true
false

請參閱

參考

function 陳述式

其他資源

JScript 函式

JScript 資料型別