用户定义的 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 数据类型