繁体   English   中英

如何返回带编号的字符串数组的元素?

[英]How can I return elements of an array in a numbered string?

我有array=[a, b, c, d] ,我想返回带编号的字符串中的元素,例如"1. a, 2. b, 3. c, 4. d"

我尝试过使用使用索引ifor循环返回"i. array[i]" ,但是我只得到返回的数组的第一个元素,而不是整个数组。

const array = ["a", "b", "c", "d"]
for (var i = 0; i < array.length; i++) {
    return `The order is currently: ${i+1}. ${array[i]}, `
}

我希望输出为"The order is currently 1. a, 2. b, 3. c, 4. d" ,但实际输出为"1. a,"

您可以将Array.map()与模板文字一起使用并加入结果。

map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。

该映射创建一个['1. a', '2. b', etc...]的数组['1. a', '2. b', etc...] ['1. a', '2. b', etc...] ['1. a', '2. b', etc...] ,则在加入时会生成请求的字符串。

 const array = ["a", "b", "c", "d"] const result = array.map((c, i) => `${i + 1}. ${c}`).join(', ') console.log(`The order is currently: ${result}`) 

您如何解决您的工作?

您需要在每次迭代中累积结果,并删除最后一个字符(多余的, ):

 const array = ["a", "b", "c", "d"] let result = 'The order is currently:' for (var i = 0; i < array.length; i++) { result = `${result} ${i+1}. ${array[i]},` } console.log(result.slice(0, -1)) 

您可以映射所需的零件,并用逗号将它们连接起来。

 const array = ["a", "b", "c", "d"] console.log(`The order is currently: ${array.map((v, i) => `${i + 1}. ${v}`).join(', ')}`); 

另一个可能的解决方案是使用Array.reduce() ,该累加器以等于字符串"The order is currently: "累加器开头,并在每次迭代中添加相关文本。 当然,您将需要进行一些后期处理以删除最新的不需要的comma

 const array = ["a", "b", "c", "d"]; let res = array.reduce( (str, v, i) => str += `${i+1}. ${v}, `, "The order is currently: " ) console.log(res.slice(0, -2)); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

在for语句中使用return将引发数组中的第一个元素。 尝试连接一个字符串,然后返回该字符串。

像这样:

const array = ["a", "b", "c", "d"];
let output = "";
for (var i = 0; i < array.length; i++) {
    output = output  + (i+1) + '. ' + array[i] + ', ';
}
console.log('The order is currently: ' + output);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM