JavaScript 如何测试一个值x对谓词函数的满足,并返回fn(x)或x的结果
在本文中,我们给出了一个值x,并且任务是检查该值是否满足谓词函数的条件。如果值满足条件或谓词函数,则返回fn(x),否则返回x。
谓词函数 是一个接受一个项作为输入并根据项是否满足该条件返回true或false的函数。
示例1
在这个示例中,我们给定了一个数字和一个条件,如果条件为真,则返回fn(number),否则返回一个简单的数值。
<script>
// Function that we have to return
function fn(x) {
let fact = 1;
for (i = 1; i <= x; i++) {
fact *= i;
}
return fact;
}
// Predicate function checking even value
function isEven(x) {
return (x % 2 === 0);
}
// Function returning fn(x) if predicate
// function return true else return x
function test(x) {
let e = isEven(x);
if (e) {
return fn(x);
} else
return x;
}
// Printing return value
let ans = test(6);
console.log(`This function returns ${ans}`);
</script>
输出: 在这里,条件是一个应该是偶数的数字,因为我们的输入数据是偶数,所以它返回 fn(6) 的值。
This function returns 720
示例2
在这个示例中,我们给出了一个数字和一个测试条件,如果条件为真,则返回 fn(number),否则仅返回 number 的值。
<script>
// Initializing the max_Integer
let max_Integer = 20;
// Function we have to return
function fn(x) {
var b = 0;
var a = 1;
var sum;
for (i = 0; i < x - 1; i++) {
sum = a + b;
b = a;
a = sum;
}
return a;
}
// Predicate function checking value
// is less than max_Integer
function isless(x) {
return (x < max_Integer);
}
// Function return fn(x) if predicate
// function return true else return x
function test(x) {
let e = isless(x);
if (e) {
return fn(x);
} else
return x;
}
// Printing return value
let ans = test(15);
console.log(`This function returns ${ans}`);
</script>
输出:
The function returns 610
示例3
在这个示例中,我们给出了一个数字和一个测试条件,如果条件为真,则返回fn(number),否则仅返回数字的值。
<script>
// Function we have to return
function fn(x) {
let j = 1;
for (i = 0; i < x - 1; i++) {
j = j * x;
}
return j;
}
// Predicate function checking
// multiple of 3
function ismultiple(x) {
return (x % 3 == 0);
}
// Function that returns fn(x) if
// predicate function return true
// else return false
function test(x) {
let e = ismultiple(x);
if (e) {
return fn(x);
} else
return x;
}
// Printing value
let ans = test(6);
console.log(`This function returns ${ans}`);
</script>
输出:
This function returns 7776
极客教程