简体   繁体   中英

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

I have array=[a, b, c, d] and I want to return the elements in a numbered string like "1. a, 2. b, 3. c, 4. d"

I have tried using a for loop using the index i to return "i. array[i]" , but I only get the first element of the array returned, not the whole array.

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

I expect the output to be "The order is currently 1. a, 2. b, 3. c, 4. d" , but the actual output is "1. a,"

You can use Array.map() with a template literal and join the results.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

The map creates an array of ['1. a', '2. b', etc...] ['1. a', '2. b', etc...] ['1. a', '2. b', etc...] , which produces the requested string when joined.

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

How can you fix your work?

You need to accumulate the results on each iteration, and remove the last character (the redundant , ):

 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)) 

You could map the wanted parts and join the items with a comma.

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

Another possible solution is to use Array.reduce() starting with an accumulator equal to the string "The order is currently: " and adding the related text on each iteration. Of course, you will need some post-processing to delete the latest unwanted 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;} 

Using the return inside the for statement will throw the first element in the array. Try to concat a string and then return the string.

Like this:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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