我们需要编写一个JavaScript函数,该函数接受一个嵌套的文字数组,并通过将字符串中存在的所有值连接到字符串将其转换为字符串。此外,在构造新字符串时,我们应该在每个字符串元素的末尾添加一个空格。
让我们为该函数编写代码-
为此的代码将是-
const arr = [
'this', [
'is', 'an', [
'example', 'of', [
'nested', 'array'
]
]
]
];
const arrayToString = (arr) => {
let str = '';
for(let i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
str += `${arrayToString(arr[i])} `;
}else{
str += `${arr[i]} `;
};
};
return str;
};
console.log(arrayToString(arr));输出结果
控制台中的输出-
this is an example of nested array