在 JavaScript 中将 f(x) 应用于每个数组元素
问题
假设,给定一个数学函数:
f(x) = ax2 + bx + c
其中 a、b 和 c 是三个常数。
我们需要编写一个 JavaScript 函数,该函数将排序好的整数数组 arr 作为第一个参数,将 a、b 和 c 作为第二个、第三个和第四个参数。该函数应将函数 f(x) 应用于数组 arr 的每个元素。
并且该函数应该返回转换后数组的排序版本。
例如,如果函数的输入为:
const arr = [-8, -3, -1, 5, 7, 9]; const a = 1; const b = 4; const c = 7;
那么输出应该是:
const output = [ 4, 4, 39, 52, 84, 124 ];
示例
代码如下:
const arr = [-8, -3, -1, 5, 7, 9];
const a = 1;
const b = 4;
const c = 7;
const applyFunction = (arr = [], a = 1, b = 1, c = 1) => {
const apply = (num, a, b, c) => {
const res = (a * (num * num)) + (b * num) + (c);
return res;
};
const result = arr.map(el => apply(el, a, b, c));
result.sort((a, b) => a - b);
return result;
};
console.log(applyFunction(arr, a, b, c));代码解释
我们首先遍历数组以将 f(x) 函数应用于每个元素,然后使用 Array.prototype.sort() 对数组进行排序,最后返回排序后的数组。
输出
控制台中的输出将是:
[ 4, 4, 39, 52, 84, 124 ]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP