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

JavaScript - null 값이 있는 배열을 문자열로 변환

<시간/>

일부 문자열 값과 일부 null 값이 포함된 배열이 있습니다.

이 배열을 받아 배열의 값을 결합하고 null 값을 생략하여 구성된 문자열을 반환하는 JavaScript 함수를 작성해야 합니다.

다음은 일부 null 및 정의되지 않은 값이 있는 배열입니다. −

const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];

이 함수의 코드를 작성해 봅시다 -

예시

const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of",
"a", null, "sentence"];
const joinArray = arr => {
   const sentence = arr.reduce((acc, val) => {
      return acc + (val || "");
   }, "");
   return sentence;
};
console.log(joinArray(arr));

출력

다음은 콘솔의 출력입니다 -

Hereisanexampleofasentence