使用 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 出阁宴祝福语姐姐简短