如何从字符串中获得奇数和偶数位置字符?
我们必须编写一个函数,该函数从字符串中删除每隔一个字符(从第一个字符开始),并在JavaScript的末尾附加所有已删除的字符。
例如-
If the string is "This is a test!" Then it should become "hsi etTi sats!"
因此,让我们为该函数编写代码-
示例
const string = 'This is a test!';
const separateString = (str) => {
const { first, second } = [...str].reduce((acc, val, ind) => {
const { first, second } = acc;
return {
first: ind % 2 === 1 ? first+val : first,
second: ind % 2 === 0 ? second+val : second
};
}, {
first: '',
second: ''
})
return first+second;
};
console.log(separateString(string));输出结果
控制台中的输出将为-
hsi etTi sats!
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短