我的輸入是一個多維陣列,我希望陣列中的所有內容都在一個字串中 -
輸入 -
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,,1]]
預期輸出
"123,132,321,312,213,231"
我努力了
input.join() // which gives me
"1,2,3,1,3,2,3,2,1,3,1,2,2,1,3,2,3,1"
而且我也試過
input.join('') // which gives me
"1,2,31,3,23,2,13,1,22,1,32,3,1"
我也嘗試過為此使用for回圈
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
let output = ''
for (let i = 0; i < input.length; i ){
let result = input[i]
output = result.toString()
}
哪個回傳
"123132321312213231"
我似乎無法破解這個......任何提示?
謝謝
uj5u.com熱心網友回復:
可以簡單地使用.map()with .join('')inside 來實作:
const input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,,1]];
const result = input.map(arr => arr.join('')).join();
console.log(result);
當您將空字串傳遞''給時.join(),所有元素都將連接在一起,它們之間沒有任何字符。
uj5u.com熱心網友回復:
你的 for 回圈幾乎就在那里
我上面的用戶的另一個解決方案在我看來更好
但是在這里使用您的系統,您可以執行以下操作:
let input = [[1, 2, 3], [1, 3, 2], [3, 2, 1], [3, 1, 2], [2, 1, 3], [2, 3, 1]]
let output = ''
// since we are working with an array why not use forEach, but you can also go with a normal for, or for of etc
input.forEach((array) => {
// here we could another forEach for example
array.forEach(number => { // adding all numbers inside the smaller array to one string
output = number;
})
output = ','
})
output = output.slice(0, output.length - 1)
給出輸出:
"123,132,321,312,213,231"
uj5u.com熱心網友回復:
Array.prototype.join()是您要查找的內容,但是要在沒有任何分隔符的情況下連接每個陣列元素,需要一個空字串array.join(""):
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
let stringified2DArray = ""
for (let i in input) {
if (i == input.length-1) stringified2DArray = input[i].join("")
else stringified2DArray = input[i].join("") ','
}
console.log(stringified2DArray)
在上面的例子中,我們回圈遍歷每個內部陣列,連接每個元素,然后添加逗號。如果它是回圈中的最后一次迭代,我們排除逗號以避免尾隨逗號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414924.html
標籤:
