简体   繁体   English

参数和论点。 如何返回包含数组中所有项目的句子?

[英]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"].如果我传入“best fruits”作为参数,我希望它返回条件中的相应字符串和数组 ["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?我如何让它返回相应 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.您根本不需要循环,只需使用Array.prototype.join将数组值连接成一个字符串即可。 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:您甚至可以通过不对字符串中的长度进行硬编码并使用提供的实际数组长度来改进它,这意味着您甚至不需要if条件:

 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:您不需要使用 for,只需像下面那样使用 join:

 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(",")}, ` } }

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

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