为什么它显示为未定义?

时间:2020-04-04 20:24:53

标签: javascript

运行流时,它会抛出undefined

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 selector = 0
const choiceLight = []
const choiceMedium = []
const choiceDark = []

for (const roast of coffees) {
    if (roast.includes("light")) {
      choiceLight.push(roast)
      console.log("I'll have the " + choiceLight[selector] + " and drink it black") 
    } else if (roast.includes("medium")) {
      choiceMedium.push(roast)
      console.log("I'll have the " + choiceMedium[selector] + " and add cream only")
    } else if (roast.includes("dark") || roast.includes("espresso")) {
      choiceDark.push(roast)
      console.log("I'll have the " + choiceDark[selector] + " and add cream and sugar" )
    }
    selector++
}

/*
I'll have the light colombian roast and drink it black
I'll have the undefined and add cream and sugar
I'll have the undefined and add cream only
I'll have the undefined and add cream and sugar
I'll have the undefined and add cream and sugar
I'll have the undefined and add cream only
I'll have the undefined and drink it black
I'll have the undefined and add cream and sugar
*/

4 个答案:

答案 0 :(得分:2)

您将数据推送到另一个数组中。推送将推送最后的数据。因此索引将不同。 例如:在第二个数据中,您推入choiceMedium,因此索引将为0,但是selector将为1。所以undefined

正确的实施方式:

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 selector = 0;
const choiceLight = [];
const choiceMedium = [];
const choiceDark = [];

for (const roast of coffees) {
  if (roast.includes("light")) {
    choiceLight.push(roast);
    console.log(
      "I'll have the " + roast + " and drink it black"
    );
  } else if (roast.includes("medium")) {
    choiceMedium.push(roast);
    console.log(
      "I'll have the " + roast + " and add cream only"
    );
  } else if (roast.includes("dark") || roast.includes("espresso")) {
    choiceDark.push(roast);
    console.log(
      "I'll have the " + roast + " and add cream and sugar"
    );
  }
  selector++;
}
.as-console {
  min-height: 100% !important;
}

.as-console-row {
  color: blue !important;
}

答案 1 :(得分:0)

在第一次迭代中,selector等于零。没问题。您将给定的品种附加到选择数组,并打印其 0索引元素。(第一个位置)

在第二次迭代中,selector等于1。除非它与先前的迭代属于同一选择数组,否则您将其追加到一个空数组并请求其为 1个索引元素(因此,第二名)。它不存在。

在任何发现与上一个选项不属于同一选择的变量的情况下,数组索引将永远不会再与选择器值匹配。

答案 2 :(得分:0)

每次循环时,您将递增selector,但是您仅将一项推入每个数组。因此,每个项目在每个数组中都将位于位置0。如果您将selector设置为0,则应该可以使用

答案 3 :(得分:0)

为什么根本需要使用“选择器”?
您可以按“烤”并打印“烤”评论

如前所述,您有单独的列表,但在所有循环迭代中使用一个索引“选择器”

如果您要使用“选择器”,则可以针对每种烘烤类型使用一种:ltSelector,mdSelector,dkSelector。