查找其后继者和前任者在JavaScript中处于数组中的元素
我们需要编写一个JavaScript函数,该函数将整数数组作为第一个也是唯一的参数。
该函数应构造并返回一个新数组,该数组包含原始数组中所有此类元素的后继者和前任者都存在于该数组中。如果意思是,如果原始数组中有任何元素num,则当且仅当数组中还存在num-1和num+1时,才应将其包括在结果数组中。
例如-
如果输入数组是-
const arr = [4, 6, 8, 1, 9, 7, 5, 12];
那么输出应该是-
const output = [ 6, 8, 7, 5 ];
示例
为此的代码将是-
const arr = [4, 6, 8, 1, 9, 7, 5, 12];
const pickMiddleElements = (arr = []) => {
const res = [];
for(let i = 0; i < arr.length; i++){
const num = arr[i];
const hasBefore = arr.includes(num - 1);
const hasAfter = arr.includes(num + 1);
if(hasBefore && hasAfter){
res.push(num);
};
};
return res;
};
console.log(pickMiddleElements(arr));输出结果控制台中的输出将是-
[ 6, 8, 7, 5 ]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下