返回数组中每个单独的元素为纯字符串



我有一个包含几个字符串的数组。我想循环遍历它并将结果存储在一个变量中,我将在另一个组件中作为prop访问该变量。我希望输出是单独字符串的形式,而不是返回一个数组。我可以使用forEach,它以我想要的方式返回我的输出,但是我们不能在forEach中返回任何东西,因为它总是未定义的。

array = ['this', 'is', 'an', 'example']
array.forEach(elem => console.log(elem)) // prints: this
//is
//an
//example

我如何返回像这里所示的输出数组的各个项目,并将其存储在一个变量中?我尝试了传统的for循环,但它返回第一个元素(我做了一些挖掘,发现我们可以使用闭包,但它没有解决我的问题,将它存储在一个变量中)。我觉得解决方案很简单,我不必要地把它复杂化了,任何帮助都是非常感谢的。谢谢你。

编辑:我的预期输出是:

this
is
an
example

我想接收数组的每个项目作为一个单独的字符串,需要在一个变量中存储这些值。对不起,我没说清楚。

我认为你想用换行符来join数组。

它应该是这样工作的:

let array = ['this', 'is', 'an', 'example']
let result = array.join('n')
console.log(result);


我不确定我是否理解了,但我会给你一些例子,希望你能使用其中一个。

var array = ['this', 'is', 'an', 'example'];
console.log(array.join(' ')); //this is an example
console.log(array.toString()); //this,is,an,example
console.log(array.join('')); //thisisanexample
console.log(array.join('-')); //this-is-an-example

我不知道关于单独的变量,但如何一个对象与单独的键?

let array = ['this', 'is', 'an', 'example'];
const obj = {};
for (let i = 0; i < array.length; i++) {
obj[i] = array[i];
};

…但这真的有必要吗?你已经可以通过索引访问数组中的每个字符串:
array[0]; // this
array[1]; // is