使用 JavaScript 拆分数字以包含连续的奇数或偶数
问题
我们需要编写一个接受数字n(n>0)的JavaScript函数。我们的函数应该返回一个包含奇数或偶数连续部分的数组。这意味着当我们遇到不同的数字(奇数为偶数,偶数为奇数)时,我们应该在位置处拆分数字。
示例
以下是代码-
const num = 124579;
const splitDifferent = (num = 1) => {
const str = String(num);
const res = [];
let temp = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(!temp || +temp[temp.length - 1] % 2 === +el % 2){
temp += el;
}else{
res.push(+temp);
temp = el;
};
};
if(temp){
res.push(+temp);
temp = '';
};
return res;
};
console.log(splitDifferent(num));输出结果[ 1, 24, 579 ]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短