过滤数组以包含JavaScript中的回文元素
我们需要编写一个JavaScript函数,该函数接受String/Number文字数组,并返回原始数组中所有属于回文元素的子数组。
例如
如果输入数组是-
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
那么输出应该是-
const output = [12321, 'did'];
我们将创建一个接收数字或字符串并检查其是否为布尔值的辅助函数。
然后,我们将遍历数组,过滤回文元素,然后返回过滤后的数组。
因此,让我们为该函数编写代码-
示例
为此的代码将是-
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
const isPalindrome = el => {
const str = String(el);
let i = 0;
let j = str.length - 1;
while(i < j) {
if(str[i] === str[j]) {
i++;
j--;
} else {
return false;
}
}
return true;
};
const findPalindrome = arr => {
return arr.filter(el => isPalindrome(el));
};
console.log(findPalindrome(arr));输出结果
控制台中的输出将为-
[ 12321, 'did' ]
热门推荐
7 圆圆的祝福语简短
9 短祝福语简短暖心
10 离校退群祝福语简短
11 收生日红包祝福语 简短
12 近代生日祝福语简短精辟
13 特别的端午祝福语简短
14 国庆求婚祝福语简短精辟
15 分手祝福语简短短句
16 送笔筒的祝福语简短
17 离别简短的祝福语大全
18 学生节祝福语大全简短