gpt4 book ai didi

javascript - 嵌套数组到字符串javascript

转载 作者:行者123 更新时间:2023-11-30 14:50:03 24 4
gpt4 key购买 nike

我对如何将嵌套数组转换为字符串感到困惑,但字符串中仍然有数组,有人可以帮我吗?

输入:[["Jimmy", 30, ["Ford", "BMW", "Fiat"]], ["Fiona", 25, ["Ford", "BMW", "Fiat"]], ["Anny", 19, ["Ford", "BMW", "Fiat"]], ["Gabby", 27, ["Ford", "BMW", "Fiat"]], ["Kevin ", 20, ["福特", "宝马", "菲亚特"]]]

预期输出:

"Jimmy,30,[Ford,BMW,Fiat]
Fiona,25,[Ford,BMW,Fiat]
Anny,19,[Ford,BMW,Fiat]
Gabby,27,[Ford,BMW,Fiat]
Kevin,20,[Ford,BMW,Fiat]"

谢谢

最佳答案

我们可以只使用递归函数将任何数组中的任何内容存储在一个字符串中,然后从该函数返回该字符串。

function printArr(arr) {
let str = "";
for (let item of arr) {
if (Array.isArray(item)) str += printArr(item);
else str += item + ", ";
}
return str;
}

console.log(
printArr([
["Jimmy", 30, ["Ford", "BMW", "Fiat"]],
["Fiona", 25, ["Ford", "BMW", "Fiat"]],
["Anny", 19, ["Ford", "BMW", "Fiat"]],
["Gabby", 27, ["Ford", "BMW", "Fiat"]],
["Kevin", 20, ["Ford", "BMW", "Fiat"]]
])
);

关于javascript - 嵌套数组到字符串javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48287178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com