过滤数组以包含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' ]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短