gpt4 book ai didi

javascript - 将数组转换为字符串,并添加数组每个元素的数字?

转载 作者:行者123 更新时间:2023-12-01 01:25:47 27 4
gpt4 key购买 nike

var array = ['a', 'b', 'c']
function arrayTransform(array) {
if (array.lengths === 0) {
console.log("Empty")
} else {
console.log(array.join());
}
}

arrayTransform(array);

结果应该是 1.a, 2.b, 3.c我得到 abc

最佳答案

似乎您想要将索引添加到元素中。在这种情况下,使用 map 函数将返回一个数组,然后使用 join 创建最终字符串

var array = ['a', 'b', 'c']

function arrayTransform(array) {
if (array.lengths === 0) {
console.log("Empty")
} else {
return array.map((item, index) => {
return `${index+1}.${item}` // template literals

}).join()
}
}

console.log(arrayTransform(array));

关于javascript - 将数组转换为字符串,并添加数组每个元素的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53819133/

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