假设我们有两个数字数组,它们代表两个这样的范围-
const arr1 = [2, 5]; const arr2 = [4, 7];
我们需要编写一个接受两个这样的数组的JavaScript函数。
然后,该函数应创建一个范围的新数组,即输入范围和返回范围的交集。
因此,上述输入的输出应如下所示:
const output = [4, 5];
为此的代码将是-
const arr1 = [2, 5];
const arr2 = [4, 7];
const findRangeIntersection = (arr1 = [], arr2 = []) => {
const [el11, el12] = arr1;
const [el21, el22] = arr2;
const leftLimit = Math.max(el11, el21);
const rightLimit = Math.min(el12, el22);
return [leftLimit, rightLimit];
};
console.log(findRangeIntersection(arr1, arr2));输出结果
控制台中的输出将是-
[ 4, 5 ]