简体   繁体   中英

Parameters and arguements. How do I return the sentence with all the items in the array?

If I pass in "largest countries" as an argument, I want it to return the respective string in the condition and all the countries in this array ["China", "India", "USA"]. If I pass in "best fruits" as an argument, I want it to return the respective string in the condition and all the fruits in this array ["Apples", "Bananas"].

My code doesn't do that. It returns just one country, the first one or just one fruit, the first one. How do i get it to return all the items in the respective arrays?

 let sentenceC = document.getElementById("constructed") function generateSentence(desc, arr) { for (let i = 0; i < arr.length; i++) { if (desc === "largest countries") { return `The 3 ${desc} are ${arr[i]}, ` } else if (desc === "best fruits") { return `The 2 ${desc} are ${arr[i]}, ` } } } sentenceC.innerHTML = generateSentence("largest countries", ["China", "India", "USA"])
 <p id="constructed"></p>

You don't need a loop at all, and can just use Array.prototype.join to join the array values into a string. For example:

 let sentenceC = document.getElementById("constructed") function generateSentence(desc, arr) { if (desc === "largest countries") { return `The 3 ${desc} are ${arr.join(', ')}` } else if (desc === "best fruits") { return `The 2 ${desc} are ${arr.join(', ')}` } } sentenceC.innerHTML = generateSentence("largest countries", ["China", "India", "USA"])
 <p id="constructed"></p>

You can even improve it by not hard-coding the lengths in your string and using the actual array length provided, which means you don't even need the if condition:

 let sentenceC = document.getElementById("constructed") function generateSentence(desc, arr) { return `The ${arr.length} ${desc} are ${arr.join(', ')}` } sentenceC.innerHTML = generateSentence("largest countries", ["China", "India", "USA"])
 <p id="constructed"></p>

You don't need to use for, just use join like bellow:

 function generateSentence(desc, arr){ if(desc === "largest countries"){ return `The 3 ${desc} are ${arr.join(",")}, ` } else if (desc === "best fruits"){ return `The 2 ${desc} are ${arr.join(",")}, ` } }

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