Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

문자열에서 홀수 및 짝수 위치 문자를 얻는 방법은 무엇입니까?

<시간/>

문자열에서 모든 두 번째 문자(첫 번째 문자부터 시작)를 제거하고 제거된 모든 문자를 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!