使用 forEach 方法使用模板文字创建字符串

Create Strings using Template Literals using forEach Method

有人可以帮助我修复我的代码吗?我在这个练习中使用了 forEach 方法

我想我已经接近了,但它仍然给我未定义,它已经在 result.failure 中,因为我通过添加另一个 string/num.

来检查
const result = {
  success: ["max-length", "no-amd", "prefer-arrow-functions"],
  failure: ["no-var", "var-on-top", "linebreak",],
  skipped: ["no-extra-semi", "no-dup-keys"]
};
function makeList(arr) {
  // Only change code below this line
  const failureItems = [];

  const results = arr.forEach(k => failureItems.push(`<li class="text-warning">${arr[k]}</li>`));


  // Only change code above this line

  return failureItems;
}

const failuresList = makeList(result.failure);
console.log(failuresList);

应该是这样

[
  '<li class="text-warning">no-var</li>',
  '<li class="text-warning">var-on-top</li>',
  '<li class="text-warning">linebreak</li>'
]

但在这段代码中我的结果是这样

[ '<li class="text-warning">undefined</li>',
  '<li class="text-warning">undefined</li>',
  '<li class="text-warning">undefined</li>' ]

您想连接 k。同样如评论中所述,Array#forEach returns undefined.

要解决以上问题:

arr.forEach(k => failureItems.push(`<li class="text-warning">${k}</li>`));

另一种使用 Array#map 的解决方案:

function makeList(arr) {
  return arr.map(k => `<li class="text-warning">${k}</li>`);
}

const result = {
  success: ["max-length", "no-amd", "prefer-arrow-functions"],
  failure: ["no-var", "var-on-top", "linebreak",],
  skipped: ["no-extra-semi", "no-dup-keys"]
};

const failuresList = makeList(result.failure);

console.log(failuresList);