如何从字符串中获取奇数和偶数位置的字符?
javascriptweb developmentobject oriented programming更新于 2025/10/3 7:08:17
我们必须编写一个函数,从字符串中删除每个第二个字符(从第一个字符开始),并在 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!
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

