我有一個包含幾個字串的陣列。我想遍歷它并將結果存盤在一個變數中,我將在另一個組件中作為道具訪問該變數。我希望輸出采用單個字串的形式,而不是回傳陣列。我可以使用 forEach 并以我想要的方式回傳輸出,但是我們不能在 forEach 中回傳任何內容,因為它總是未定義的。
array = ['this', 'is', 'an', 'example']
array.forEach(elem => console.log(elem)) // prints: this
//is
//an
//example
如何回傳陣列的各個專案(如此處顯示的輸出)并將其存盤在變數中?我嘗試了一個傳統的 for 回圈,但它回傳第一個元素(我做了一些挖掘,發現我們可以使用閉包,但它沒有解決我將它存盤在變數中的問題)。我覺得解決方案很簡單,我不必要地將其復雜化,非常感謝任何幫助。謝謝你。
編輯:我的預期輸出是:
this
is
an
example
我想將陣列的每個專案作為單獨的字串接收,并且需要將這些值存盤在一個變數中。抱歉不清楚。
uj5u.com熱心網友回復:
我不確定我是否明白,但我會給你一些例子,希望你可以使用其中的一個。
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
uj5u.com熱心網友回復:
我認為您想要join帶有換行符的陣列。
這是它應該如何作業:
let array = ['this', 'is', 'an', 'example']
let result = array.join('\n')
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/310948.html
標籤:javascript 数组 反应 循环
上一篇:使用Jest在Next.JS中測驗ClientPortal
下一篇:Chart.js縮放顯示小數點
