【发布时间】:2021-01-13 08:50:35
【问题描述】:
我刚刚开始学习 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
有人介意看看我做错了什么吗?希望我的指导有意义。
【问题讨论】:
标签: javascript arrays methods include for-of-loop