我刚刚开始学习 JavaScript,所以这对我来说可能是一个简单的错误,但我遇到的问题是我应该为每个数组中的每个字符串打印不同的指令到控制台,并且当我运行我的现在,它每次都重复相同的元素,并在每次迭代时将下一个字符串添加到它们,而不是为新数组中的每个单独的字符串提供指令。
这是我的代码:
const coffees = [
"light colombian roast", "hawaiian dark roast", "guatemalan blend medium roast",
"madagascar espresso roast", "jamaican dark blue", "jamaican medium roast",
"salvador robusto light", "bali espresso roast"]
let lightRoast = []
let medRoast = []
let darkOrEspresso = []
for (const roast of coffees)
{
if (roast.includes("light") )
{
lightRoast.push(roast)
console.log(`I'll have the ${lightRoast} and drink it black`)
}
else if (roast.includes("medium"))
{
medRoast.push(roast)
console.log(`I'll have the ${medRoast} and add cream only`)
}
else if (roast.includes("dark") || roast.includes("espresso"))
{
darkOrEspresso.push(roast)
console.log(`I'll have the ${darkOrEspresso} and add cream and sugar`)
}
}
我试图让控制台为新数组中的每个单独的字符串打印这些指令,这取决于它是在 light、med 还是 dark 数组中:
"I'll have the xxx and drink it black"
"I'll have the xxx and add cream only"
"I'll have the xxx and add cream and sugar"
但相反,我得到这样的结果,其中字符串位于正确的数组中,但被添加到彼此之上,而不是每个都有自己的行:
I'll have the light colombian roast,salvador robusto light and drink it black
I'll have the guatemalan blend medium roast,jamaican medium roast and add cream only
I'll have the hawaiian dark roast,madagascar espresso roast,jamaican dark blue,bali espresso roast and add cream and sugar
有人介意看看我做错了什么吗?希望我的指导有意义。